-
[weird JavaScript] type coercion, ==와 > < operator, ++, --도 type coercion 사용컴퓨터/JavaScript_typescript 2020. 2. 11. 13:57
* 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?
'컴퓨터 > JavaScript_typescript' 카테고리의 다른 글
How to make an exact copy of an element? (0) 2020.03.25 [JavaScript] Object.freeze : 객체를 불변하게 만들기, const(reference 규제)와의 차이점(freeze: 값을 규제) (0) 2020.02.11 [javascript] Objects.keys(array), Object.getOwnPropertyNames(array), Object.entries(array) (0) 2020.02.06 JSON - parsing error (0) 2020.01.21 동적 타이핑, 타입 체크 (0) 2020.01.19