Chapter 9 타입 변환과 단축 평가

Type Conversion and Short-Circuit Evaluation

  • 😎 의도적 타입 변환: (명시적 타입 변환, type casting, explicit coercion)
  • 🦹🏻‍♀️ 암묵적 타입 변환: (묵시적 타입 변환, type coercion, implicit coercion)

암묵적 type 변환

평가 도중 🤖 엔진에 의해 암묵적으로 타입 변환 발생 (개발자 의사 없이도..)

  • primitive values 는 immutable 하기에 실제 type 이 변경되는게 아니라, 새로운 값을 생성해서 반환함
  • 새로운 원시 값은 생성되고 사용되면 버려짐 ㅠㅠ
  • JS 는 가급적 에러를 발생시키지 않도록 암묵적 타입 변환을 많이많이 지원함

  • 암묵적 타입 변환이 발생하는 경우

    • ( x + ‘’ ) => 문자열 변환
    • ( x (-,*,/,>,<..) 0 ) => 숫자 변환
    • ( +x ) => 숫자 변환 ( 단항 + ), +[] => NaN
    • ( x == true/false/null/undefined/NaN/Infinity ) => boolean 변환
  • truthy, falsy 값 -> other type type coerced into boolean
    • falsy check: const isFalsy = !value
    • truthy check: const isTruthy = !!value

명시적 type 변환

개발자가 의도적으로 타입을 변환하는 것

  • built-in 생성자 함수 사용 (String, Number, Boolean, Symbol, BigInt, Object)

    • 생성자 함수는 생성된 인스턴스를 반환함
  • .toString(), .toNumber(), .toBoolean() 메서드 사용

  • + '', - 0, +x, 등등

단축 평가

  • 평가 도중 결과가 확정됨 -> 나머지 평가 생략함
  • 논리 연산자에서 주로 사용됨

    • 논리곱 (&&), 논리합 (||) 은 피연산자 type 변환 안하고 그대로 반환함
  • optional chaining
  • nullish coalescing
    • const a = '' || 'default'; // ‘default’
    • const a = '' ?? 'default'; // ‘’