컴퓨터/JavaScript_typescript

[weird JavaScript] type coercion, ==와 > < operator, ++, --도 type coercion 사용

수제녹차 2020. 2. 11. 13:57
728x90
반응형

* type coercion

automatically convert a value from one data type to another when using some sort of operator with it

 

var html1 = 2+" Hello, world." // "2 Hello, world"

 

* ==(equals) vs ===(strict equals)

Strict equals (===) check that items have both the same value and the same data type.

ex) '42' === 42 : false

Regular equals (==) uses type coercion to compare the values of the items, ignoring their data type.

 

greater than/less than operators will coerce strings into numbers to check their relative value.

// returns true

'5' > 2;

 

++, -- 도 string을 number로 type coercion

var num = '5';
num++; // 6

 

JavaScript coerces the array into a string, and then the mathematical operators coerce the string into a number.

Since the array is empty, its value is 0

var increment = [];
increment++; // 1

 

var sum = + 3; // 3

var compare1 = []> 3 // 0>3이 되어 false

 

var compare2 = 3 > []; // 3>0이 되어 true

 

JavaScript again coerces the array into a string, 1,2,3. It then treats the + as a join operator, and coerces the 4 into a string.

// returns "1,2,34"
var sum = [1, 2, 3] + 4;

 

* Type coercion은 위험!

use native type conversion methods to force values into their desired format

parseFloat(변수), 변수.toString()

var sum2 = parseFloat(num1) + parseFloat(num2)

var str2 = val1.toString() + val2.toString();

 

나도 css 먹이려고 pagination 코드에서 tag selecting 하려다 number여야하는 것을 string으로 바꿔버렸다.

그 결과 페이지 넘길 때 에러가 발생하고 말았다.

주의해야지~~

 

source: Chris Ferdinandi, [Go Make Things] What is type coercion in vanilla JavaScript?

반응형