Coercion
Converting a value from one type to another: Happens quite often in Javascript because it is Dynamically type
Example :
var a = 1 + '2'
What we get is 12 because the first value (1) was coerced by the Engine into a String,
in memory the string 1 and the number one look nothing alike.
The Javascript Engine knows when you call + with a number and a string,
it tries to coerced from number 1 to string representation of 1.
Number function converts any value to a number (coerced)
Number(false) = 0
Number(undefined) = NaN (Not a number - not a Primitive type but can be treated as such)
Number(null) = 0
Comparison Operators
Comparison Operators:
console.log( 1 < 2 < 3) ;
true
console.log( 3 < 2 < 1) ;
true - Why is it true?
- Because of its Associativity
- (Left-to-right - One furthest to the left will get run first),
so 3 < 2 = false and then false < 1 = true
- Try to coerced false into a number = 0
- true = 1 , false = 0
- So whats its really doing is 0 < 1 = false
Example because of Coercion and Comparison
Equality:
3 == 3 : true
"3" == 3 : true
false == 0 : true
null == 0 : false
null < 1 : true
"" == 0 : true
"" == false : true
We need to use strick equality === to fix the unexpected behavior of equality
- Does not try to coerced the values
- Two values are not the same type will result to false
- 3 === 3 : true
- "3" === 3 : false