33 JavaScript Concepts - type coercion(강제 형 변환)


이 문서는 33 Concepts Every JavaScript Developer Should Know 주제로 노마드 코더(Nomad Coders)님이 강의한 내용을 정리하였습니다.


type coercion(강제 형 변환)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
console.log(4 + "hello"); // 4hello

console.log(4 + 4 + "hello"); // 8hello
console.log("" == true); // false
console.log(1 == true); // true
console.log(66 + true); // 67

console.log(66 + true); // 67
console.log(66 + 1); // 67
console.log(66 + false); // 66
console.log(66 + 0); // 66

// true -> 1, false -> 0이 된다.
console.log(55 - true); // 54
// console.log(55 - 1); // 54

console.log(55 - false); // 0
// console.log(55 - 0); // 0
  • 항상 더하기(+)가 모든 걸 숫자로 바꾸는 것은 아니다.

  • 만약 여기 string이 있으면 이렇게 ‘66false’이 된다.

  • 하나의 string 으로 인식한다.
1
console.log(66 + "false"); // 66false
  • 오직 덧셈 연산에서만 이렇게 덩어리가 된다.
  • -> loaded operator라고 한다.

  • 자바스크립트는 왼쪽에서 오른쪽으로 연산이 일어난다.

1
2
3
4
console.log(10 + 66 + "false"); // 76false
// 1) 숫자 10과 66의 덧셈 연산이 이루어져서 76이 된다.
// 2) 그 다음 false와의 덧셈 연산(76+"false")이 이루어지는데, "false"가 string이므로
// 결과는 "76string"이 된다.
  • 뺄셈 연산에서는 string이 있으면 string을 number로 강제 형변환 한다.
1
2
3
console.log(25 - "1"); // 24

// 뺄셈 연산이 있으므로 string인 "1"이 숫자1로 강제로 형변환 된다.
  • 곱셈 연산도 뺄셈 연산과 마찬가지로 string이 있으면 number로 강제 형변환 한다.
1
2
console.log(25 * "2"); // 50
console.log(25 * "string"); // NaN
1
2
3
4
5
6
7
8
9
console.log("" == true); // false
// 텅빈 문자열은 거짓
// 텅빈 문자열은 제로 바이트이다.
// 이걸 0으로 변환 시킨다.
console.log(0 == true); // false
// 0은 거짓이다.
console.log(NaN == true); // false
console.log(undefined == true); // false
console.log(null == true); // false
  • ==보다는 ===를 주로 사용한다.
  • ===를 사용하면 type coercion이 일어나지 않는다.
1
2
3
4
console.log("1" == 1); // true
// '=='를 사용해서 "1"이 숫자 1로 강제 형변환되었기 때문에 '참'이 된다.
console.log("1" === 1); // false
// "==="를 사용했기 때문에 Type coercion
1
2
3
4
5
6
7
8
9
10
11
console.log("true" == true); // false
console.log("1" == 1); // true
// string "true"는 거짓인데, 왜 string "1"는 참일까?
// "=="이 boolean을 만나면 숫자로 변환한다.
console.log("true" == 1);
// -> true가 1이 된다. 또한 앞에서 string을 숫자로 변환하려고 한다.
console.log(parseInt("true")); // NaN
// 보다시피, "true"는 숫자가 되지 않는다.
console.log(NaN == 1);
// -> 뒷단의 true는 1이 되고, 앞단의 "true"는 숫자가 안되니까 NaN이 된다.
// NaN == 1을 시도한 것이므로 이는 당연히 거짓이 된다.
  • ==boolean을 만나면, 모든 게 숫자로 변환되고 이상하고 복잡해진다.
  • -> 때문에 ==을 쓰지 않고 ===을 사용한다.
  • 이렇게 ===를 이용하면 강제 형변환을 피할 수 있다.
1
2
3
4
5
const hello = "";

if (hello) {
console.log("hello");
}
  • 위의 코드는 hello에 빈 문자열""이 들어있을 때는 if문의 조건이 false가 되어 실행되지 않게 된다.
  • 아래와 같이 변경해줘야(===!==로 비교)안전하다는 걸 알 수 있다.
1
2
3
if (typeof hello !== undefined) {
console.log("hello");
}

참고 링크