타입 변환

명시적 타입변환(explict coercion) or 타입 캐스팅(type casting) → 개발자가 의도적으로 값의 타입을 변환하는 것

암묵적 타입변환(implicit coercion) or 타입 강제 변환(type coercion) → 개발자의 의도와는 상관없이 표현식을 평가하는 도중에 자바스크립트 엔진에 의해 암묵적으로 타입이 변환되는 것

암묵적 타입변환

자바스크립트 엔진이 표현식을 평가할 때 개발자의 의도와는 상관없이 코드의 문맥을 고려해 암묵적으로 데이터 타입을 강제 변환(암묵적 타입 변환)하는 것

문자열 타입으로 변환

// 🎯 주의할 것 중심

// 숫자 타입
NaN + '';             // "NaN"
Infinity + ''         // "Infinity"

// null 타입
null + '';            // "null"

// undefined 타입
undefined + '';       // "undefined"

// 심벌 타입
(Symbol()) + '';      // TypeError: Cannot convert a Symbol value to a string

// 객체 타입
({}) + '';            // "[object Object]"
Math + '';            // "[object Math]"
[] + '';              // ""
[10, 20] + '';        // "10,20"
(function(){}_ + '';  // "function(){}"
Array + '';           // "function Array() { [native code] }"

숫자 타입으로 변환

// 문자열 타입
+ '';                  // 0
+ '0';                 // 0
+ '1';                 // 1
+ 'string'             // NaN

// 불리언 타입
+ true;                // 1
+ false;               // 0

// null 타입
+ null;                // 0

// undefined 타입
+ undefined;           // NaN

// 심벌 타입
+ Symbol();            // TypeError: Cannot convert a Symbol value to a number

// 객체 타입
+ {};                  // NaN
+ [];                  // 0
+ [10, 20];            // NaN
+ (function(){});      // NaN

불리언 타입으로 변환

자바스크립트 엔진은 불리언 타입이 아닌 값을 Truthy 값(참으로 평가되는 값) or Falsy 값(거짓으로 평가되는 값) 으로 구분한다.