Study/JS_딥다이브
[9장] 자바스크립트 딥다이브_타입 변환, 단축 평가
Minhhk
2023. 11. 23. 16:04
명시적 타입 변환 , 타입 캐스팅 → 개발자가 의도적으로 값의 타입을 변환 하는 것
암묵적 타입 변환, 타입 강제 변환 → 개발자 의도와 상관 없이, js엔진에 의한 변환
fasly 값 :
false, undefined, null, 0, -0, NaN, ‘’
// 문자열 변환
String(1); // “1”
(1).toString() // "1"
1 + '' ; // "1"
// 숫자 변환
Number('1') // 1
parseInt('1') // 1
+'1' // 1
+true // 1
'1'* // 1
// 불리언 변환
Boolean('x') // true
Boolean('1') // true
Boolean(0) // false
Boolean('') // false
Boolean(Nan, null, undefined) // false
Boolean(Infinity) // true
// 빈배열, 빈객체는 true
Boolean({}) // true
Boolean([]) // true
단축평가
// && (AND)
'Cat' && 'Dog' // "Dog"
좌 → 우항 평가 진행
마지막 ‘Dog’ true 값 출력,,
정확한 boolean 을 위해
좌항에 !! 추가
// || (OR)
'Cat'|| 'Dog' // "Cat"
좌 → 우항 평가 진행
‘Cat’ 이 true?
‘Cat’ true 값 출력
옵셔널 체이닝 연산자__ ?.
→ 좌항이 null || undefined 일 땐, undefined 반환
let str = null;
let length = str?.length
console.log(length) // undefined
→ 좌항 피연산자가 falsy 값 이라도, null || undefined 가 아니면 우항의 프로퍼티 참조
let str ='';
let length = str?.length
console.log(length) // 0
null 병합 연산자__ ??
→ 변수에 기본 값을 설정할 때
// 좌항의 피연산자가 null || undefined 이면 우항의 피연산자 반환
// 그렇지 않으면 좌항 피연산자 반환
let a = null ?? 'default'
console.log(a) // 'default'
// 이전에는 || 논리연산자로 비교 했다.
let a = '' || 'default'
console.log(a) // 'default'
👺 하지만, null 병합 연산자는 좌항의 피연산자가 falsy 값이라도,
null 과 undefined 가 아니면 좌항의 피연산자를 반환
//
let a = '' ?? 'default'
console.log(a) // ''