본문 바로가기

TIL/JAVASCRTIPT

Section2-20 Type Conversion and Coercion

"type conversion is when we manually convert from one type to another. On the other hand type coercion is when Javscript automatically converts type behind the scenes for us"

 

type conversion

직접 타입을 바꿔주는 것을 뜻한다.

const inputYear = '2020';

console.log(inputYear + 10); // 202010

console.log(Number(inputYear) + 10); // 2030

console.log(Number('hoho'));  // NaN
console.log(typeof NaN); // number

위에서 Number함수를 이용해 inputYear를 Number타입으로 바꿔주었다. 이렇게 직접 타입을 바꿔주는 것을 type conversion이라 한다. 하지만 자바스크립트에서는 자동으로 타입을 바꿔주는 type coercion이 존재하기에 type conversion은 자주 쓰이진 않는다. 

 

'hoho'를 숫자로 바꾸려하면 NaN이 뜬다. 숫자의 형태로 출력이 불가능한 경우에는 이렇게 Not a Number, 즉 NaN이 뜬다. 신기한건 이 NaN의 타입을 체크해보면 숫자라는 것이다. 큰 의미 혹은 유용성은 없을 것 같다.

 

 

type coercion

type coercion이란 자바스크립트가 자동으로 타입을 변경해주는 것을 말한다. 

 

console.log('I am' + 20 + ' years old');  // I am 20 years old

 

출력값은 코멘트 부분과 같다. 20 는 넘버타입이고 나머지는 스트링 타입임에도 에러없이 출력된다. 자바스크립트에서 자동으로 type coercion을 해준 덕분이다. '+' 오퍼레이터의 경우는 Number → String 으로 type coercion을 해준다. 다른 오퍼레이터의 경우는 어떨까?

 

console.log('23' - '10' - 3);  // 10

 

'-' 오퍼레이터의 경우 '+'와 정반대이다. String → Number로 바꿔 준다. 

 

console.log('2' * '2');  // 4
console.log('2' / '2');  // 1
console.log('10' > '2');  // true

 

나머지 경우도 마찬가지이다. 해당 연산자를 실행하기 위해선 자바스크립트는 Stirng → Number로 type coercion을 해야만 한다.

'TIL > JAVASCRTIPT' 카테고리의 다른 글

Section2-33~37 Function  (0) 2021.01.02
Section2-13 let, const, var  (0) 2021.01.02
Section2-12 Data Type  (0) 2021.01.02