IT/JavaScript

자바스크립트 타입 변환 (type conversion), 강제 형변환 (type coercion), 그리고 불리언(boolean)

김숭늉이 2023. 9. 6. 14:00
728x90

 

 

 

 

 

안녕하세요.

타입 변환 (type conversion), 강제 형변환 (type coercion), 그리고 불리언(boolean)에 대해 알아보겠습니다.

 

 

 

 


자바스크립트 타입 변환 (javascript type conversion) 

 

 

자바스크립트의 모든 밸유는 각자의 특성 즉, 타입이 있습니다. 경우에 따라 고유한 특성을 의도적으로 변형 시켜야하는 경우 가 있는데요 예를들어, 문자열을 숫자로 바꾸거나 숫자를 불리언으로 바꾸는 등의 케이스 입니다. 이러한 경우는 자바스크립트 언어 사용에 있어 항상 있는 일입니다. 

 


const inputYear = "1991"; // 문자열
console.log(inputYear + 18); // 199118 문자열 + 숫자
console.log(Number(inputYear) + 1); // 1992   ==> 문자열인 "1991"을 숫자로 타입 변환함 

console.log(Number("seung")); // NaN로 출력됨 (Not a number);
console.log(typeof NaN); // number (유효하지 않은 숫자))

console.log(String(23), 23); // 23,23 을 문자열로 변경함 / S는 항상 대문자로

 

Number() 혹은 String() 등을 통해 타입을 변경한걸 볼수 있습니다. 

const favourite = Number(prompt("What's your favourite number?")); // prompt에 작성된 값으르 저장함
console.log(favourite); // prompt에 입력한 텍스트가 나옴
console.log(typeof favourite); // string

if (favourite === 23) {
// 23 === 23
console.log("cool 23 is amazing number!");
} // 출력됨 왜냐면 favourte의 변수 타입을 숫자로 변형했기 때문에
 

 


자바스크립트 강제 형변환 (javascript type coercion)

강제 형변환의 경우는 위의 의도적으로 변환하지 않았지만 자바스크립트 내부에서 자동으로 형변환을 시키는것 을 말한다. 

이부분은 시간을 들여 어떻게 작동하는지 알아두는 것이 좋다!


console.log("I am " + 23 + " years old"); // 자동형식 강압 - 23이 문자열로 찍힘
console.log("I am " + "23" + " years old"); // 원래는 이렇게 되야 맞는것인데 23까지 문자열로 찍힘 

console.log("23" - "10" - 3); // 10 문자열이지만 숫자로 전환됨 => 마이너스가 강제형변환(type coercion)을 일으킴
console.log("23" * "2"); // 46 => 문자열이지만  숫자로 변환됨
console.log("23" / "2"); // 11.5 => 문자열이지만 숫자로 변환됨

console.log("23" + "10" + 3); // 23103  => +에는 적용되지 않음

 


let n = "1" + 1; // 11
n = n - 1; // 10
console.log(n); // 10로 찍힘
 

 

2+3+4+'5' // '95'로 콘솔에 출력  (2+3+4) + 5 = 95

'10'-'4'-'3'-2+'5' // '15'로 콘솔에 출력

 


자바스크립트 불리언 (javascript Boolean)에 대해

 

불리언은 간단하게 정리하자면 참과 거짓을 판별하는데 사용 되는것을 말합니다. 

대표 false 5가지는 0, ' ', undefined, null, NaN; 입니다. 이 5개 이외는 모두 true로 간주됩니다.

// 5 falsy values : 0, '', undefined, null, NaN; => 불리언으로 변환되면 false로 변환됨 // 나머지는 다 true

console.log(Boolean(0)); // false
console.log(Boolean(undefined)); // false
console.log(Boolean("seung")); // true
console.log(Boolean({})); // true
console.log(Boolean("")); // false

 

만약 money의 값을 0으로 지정하면 money라는 변수는 false가 되고, money를 if의 조건에 넣었을때는 else의 조건이 적용되어 콘솔창에는 'You should get a job'이 노출되게 되는 것입니다.

let money = 0;

if (money) {
// money는 false로 변환됨, 콘솔창에는 You should get a job!가 찍힘
console.log("Don't spend it all");
} else {
console.log("You should get a job!");
}

 

위의 내용과 동일하게 money의 값을 100으로 수정하면 money라는 변수는 true가 되고, money를 if의 조건에 넣었을때는 if의 조건이 적용되어 콘솔창에는 'Don't spend it all'이 노출되게 되는 것입니다.

money = 100;

if (money) {
// money는 true로 변환됨, 콘솔창에는 Don't spend it all가 찍힘
console.log("Don't spend it all");
} else {
console.log("You should get a job!");
}

 

그럼 만약 변수에 아무것도 저장하지 않았다면 어떻게 될까요? 

변수에 아무것도 저장되지 않은 상태는 undefined 이며, 이는 불리언으 false 값중 하나 입니다. 즉 false 가 됩니다. 콘솔에는 'Height is undefined'가 노출 되겠죠!

let height; // undefined 어떤 값도 지정하지 않았때문에 false
if (height) {
console.log("YAY! Height");
} else {
console.log("Height is undefined"); 
}

 

 

 

도움이 되셨나요? 

 좋은하루 보내세요~~~~🤍

728x90
반응형