형변환(Type Conversion)
String() -> 문자형으로 변환
Number() -> 숫자형으로 변환
Boolean() -> 불린형으로 변환
왜 필요할까?
"Hello" + "World" = "Hello world"
100 + 200 = 300
"100" + 200 = ?? .......의도치 않은 동작 발생할 수 있음.
ex.
const mathScore = prompt("수학 몇점?");
const engScore = prompt("영어 몇점?");
const result = (mathScore + engScore) / 2;
console.log(result);
-> 4540 도출(???사용자로부터 입력받았더니 이상한 값이 나옴)
const mathScore = 90;
const engScore = 80;
const result = (mathScore + engScore) / 2;
console.log(result);
-> 85 도출
why ???
prompt로 입력하면 무조건 문자형이 나옴.
문자와 문자를 더하면 문자가 되기 때문.
9080 / 2 = 4540
이 된 것.
어랏 9080이 문자이지만 나눗셈은 되네? -> 나누기 같은 표현식은 자동형 변환된다.
ex. "6"/"2" = 3
단, 자동 형변환 시 원인을 찾기 힘든 오류를 발생시킬 수 있으므로, 항상 의도를 가지고 원하는 타입으로 변환하는 게 좋음. 이를 명시적 형변환이라고 함.
명시적 형변환
🎀String()
console.log(
String(3),
String(true),
String(false),
String(null),
String(undefined),
)
-> "3" "true" "false" "null" "undefined"
(문자형으로 변환된 것임.)
🎀Number()
console.log(
Number("1234")
-> 1234
숫자형으로 변환된 것.
console.log(
Number("1234alskdfj")
-> NaN
console.log(
Number(true),
Number(false)
-> 1 0
🎀Boolean()
false를 반환하는 케이스
console.log(
Boolean(1),
Boolean(123),
Boolean("javascript")
)
-> true true true
console.log(
Boolean(0),
Boolean(""),
Boolean(null),
Boolean(undefined),
Boolean(NaN)
)
-> false false false false false
주의사항
Number(null) // 0
프롬프트에서 사용자로부터 나이를 입력 받을 때 그냥 취소 버튼 누르면 null이 되고, 그 null을 Number로 변환받으면 0이 된다는 점을 기억하자 !!
Number(undefined) // NaN
Boolean(0) // false
Boolean('0') // true
Boolean('') // false
Boolean(' ') // true