javascript

[javascript] #4. Type coercion(자료구조 확인)

기계학습점쟁이 2023. 2. 14. 14:00
console.log(4 + "hello");
console.log(4 + 4 + "hello");
console.log("" == true);
console.log(1 == true);
console.log(66 + true);

->

4hello

8hello

false

true

67

 

뭔가 이상한 이 식에서 우리가 알 수 있는 것은?

conversion = js가 값을 강제적으로 변화시킨다는 뜻. 개념상으로 알고 있다시피, true는 1이기 때문에 덧셈이 된다. 하지만 string이 있으면 하나의 string 덩어리로 인식한다. 예시는 하단에.

console.log(66 + "false");

-> 66false

이것을 loaded operator이라고 함

 

console.log("" == true);

-> false

텅 빈 string은 거짓.

또한 NaN, underfined, null은 거짓.

 

tip! === 사용하면 type coercion은 일어나지 않음. == 대신 쓰기. 왜냐하면 작용법이 이상해지기 때문! boolean을 만나면 모두 숫자로 변환되고 복잡스럽다... ===사용하면 이상한 규칙을 피해갈 수 있다.