[Javascript] 단항연산자 (Unary Operator)

manddu·2023년 1월 17일
post-thumbnail

단항 연산자란?

오직 하나의 피연산자만 사용하는 연산이다.

곱셉, 뺄셈, 곱셈.. 등 통상적으로 사용하는 연산들은 모두 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) 숫자가 아닌 값에 적용

  • true, false, null 값도 숫자로 변환할 수 있다.
  • 10진수, 16진수 형식의 정수에도 적용가능하다.
  • 음수에도 적용가능하나, 16진수는 예외이다.
  • Bight 값에 연산자를 적용하면 타입에러가 발생하여 NaN으로 평가된다.
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/Guide/Expressions_and_Operators#%EB%8B%A8%ED%95%AD_%EC%97%B0%EC%82%B0%EC%9E%90

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Unary_plus

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Unary_negation

profile
쉽게 터지지 않아요.

0개의 댓글