단항 더하기 - Unary plus (+)

Hanbin Lee·2021년 7월 31일
0
post-thumbnail

문자열 타입의 정수와 실수를 숫자 타입으로 변환시키는 방법은 여러가지가 있다.
그 중, 단항 더하기에 대해 작성해보려 한다.

단항 더하기 - Unary plus(+)

let a = "123";
console.log(a);  		// "123"
console.log(typeof a);  // "string"

console.log(+a);  		// 123
console.log(typeof +a); // "number"

정수와 실수형식이 아닌 null, boolean 형식에도 사용이 가능하다.

let a = null;
let b = true;
let c = false;
console.log(+a);	// 0
console.log(+b);	// 1
console.log(+c);	// 0

undefined에 연산자를 사용하면 NaN값이 나오고,
BigInt에 연산자를 사용하면 TypeError가 발생한다.

단항 부정 - Unary negation(-)

단항 부정은 단항 더하기 역할의 음수로 변환시켜준다.

let a = "123";
let b = true;
let c = false;
console.log(-a);	// -123
console.log(-b);	// -1
console.log(-c);	// -0
profile
안녕하세요 백엔드 개발자 이한빈 입니다 :)

0개의 댓글