
단항 연산자란?
오직 하나의 피연산자만 사용하는 연산이다.
곱셉, 뺄셈, 곱셈.. 등 통상적으로 사용하는 연산들은 모두 2개이상의 피 연산을 가지는 이항연산자이다.
ex) x + y, x - y
단항연산자는 이런 연산의 대상이 1개인것을 의미한다.
단항 더하기 +
단항 연산은 피연산자가 숫자일때는 아무런 동작을 하지 않는다.
그러나, 숫자가 아닌 피연산자에게는 숫자로 형 변환을 시도한다.
1) 숫자에 적용
let x = 1,
y = -1;
console.log('x: ',x,' +x: ', +x);
// Expected output ==> x: 1 +x: 1
console.log('y: ',y,' +y: ', +y);
// Expected output ==> y: -1 +y: -1
2) 숫자가 아닌 값에 적용
let i = true,
j = false,
e = '',
s = 'unary operator';
console.log('i: ',i,' +i: ', +i);
// Expected output ==> i: true +i: 1
console.log('j: ',j,' +j: ', +j);
// Expected output ==> j: false +j: 0
console.log('e: ',e,' +e: ', +e);
// Expected output ==> e: +e: 0
console.log('s: ',s,' +s: ', +s);
// Expected output ==> s: unary operator +s: NaN
단항 부정 -
피연산자의 부호를 부정한다.
즉 양수는 음수로, 음수는 양수로 변환한다.
1) 숫자에 적용
let x = 1,
y = -1;
console.log('x: ',x,' -x: ', -x);
// Expected output ==> x: 1 -x: -1
console.log('y: ',y,' -y: ', -y);
// Expected output ==> y: -1 -y: 1
2) 숫자가 아닌 값에 적용
let s = '28';
console.log('s: ',s,' -s: ', -s);
// Expected output ==> s: 28 -s: -28
리뷰
그 동안 숫자로 형 변환을 하기 위해서 Number(), parseInt(), parseFloat() 등의 메서드만을 사용하였다.
단항연산자로도 더 간단하게 형변환을 할 수 있어 유용해보인다.
출처
https://ko.javascript.info/operators#ref-86
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Unary_plus
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Unary_negation