[JavaScript 문법] 형변환

조아영·2024년 7월 22일

📌

형 변환이란 형태를 바꾸는 것을 의미합니다.

1. 암시적 형 변환

1-1. 문자열

let result1 = 1 + "2";
console.log(typeof result1, result1); // string 12

let result2 = "1" + true;
console.log(typeof result2, result2); // string 1true
// {}, null, undefined + "1" => 문자열

1-2. 숫자

let result3 = 1 - "2";
console.log(typeof result3, result3); // number -1
// 더하기 연산자 이외의 연산자는 숫자가 우선이 된다.

let result4 = "2" * "3";
console.log(typeof result4, result4); // number 6
// 더하기 연산자 이외의 연산자는 숫자가 우선이 된다.

2. 명시적 형 변환

2-1. Boolean

console.log(Boolean(0)); // false
console.log(Boolean("")); // false
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
console.log(Boolean(NaN)); // false
console.log(Boolean("false")); // true - 문자열은 비어있지 않으면 true가 나온다.
console.log(Boolean({})); // true - 객체는 값이 비어있어도 true가 나온다.

2-2. 문자열

let result5 = String(123);
console.log(typeof result5, result5); // string 123

let result6 = String(true);
console.log(typeof result6, result6); // string true

let result7 = String(false);
console.log(typeof result7, result7); // string false

let result8 = String(null);
console.log(typeof result8, result8); // string null

let result9 = String(undefined);
console.log(typeof result9, result9); // string undefined

2-3. Number

let result10 = Number("123");
console.log(typeof result10, result10); // number 123

0개의 댓글