Seung Hun

모던 자바스크립트 Deep Dive로 공부를 하면서 새롭게 알게 된 내용들을 간단하게 정리하려고 합니다.

연산자

연산자의 사이드 이팩트 및 실행 순서

++, **—**연산자는 사이드 이팩트가 존재한다. 또한 연산자의 위치에 따라서 달라질 수 있다.

let a; let b = 1; console.log('a', a, b); // undefined 1 // 먼저 b를 증가시키고 a에 할당 a = ++b; console.log('b', a, b); // 2 2 // 먼저 a에 b를 할당하고 b를 증가시킴 a = b++; console.log('c', a, b); // 2 3

+ 연산자

+ 연산자는 신기하게 string인 number를 number로 바꿀 수 있다.

let a = '1'; console.log(typeof a); // string console.log(typeof +a); // number let b = 'b'; console.log(typeof b); // string console.log(+b); // NaN

신기하다.

NaN은 NaN이 아니다.

console.log(NaN == NaN); // false console.log(NaN === NaN); // false console.log(isNaN(NaN)); // true

isNaN 을 사용하도록 하자.

+0은 -0과 같다

console.log(+0 === -0); // true console.log(+0 == -0); // true

고등학교 수학시간에 배웠던 극한이 생각이 난다.

Object.is를 통해 NaN, 0 비교를 정확하게 할 수 있다.

console.log(Object.is(+0, -0)); // false console.log(Object.is(NaN, NaN)); // true

할당문은 오른쪽부터 평가된다.

let a, b, c; let d = 4; a = d = b = c = 3; console.log(a, b, c, d); // 3 3 3 3

자연스럽게 왼쪽부터 평가된다고 생각하면 4, undefined, 3, undefined이 나올 것이라고 생각할 수 있다.

변수를 선언전에 typeof를 사용하는 경우

console.log(a); // ReferenceError: a is not defined console.log(typeof a); // undefined console.log(typeof b); // ReferenceError: b is not defined const b = 'b';

언어가 참 그렇다. const, let을 꼭 사용해서 변수를 선언하자.

지수 연산자의 우선순위

console.log(2 * 2 ** 3); // 16

지수 연산자의 우선순위는 * 보다 높다.