JS WAT
Surprising parts of JavaScript
What to expect from the talk?
Will it be useful?
Maybe a little bit ;)
Why I am here?
- To see some crazy examples of JS behaviour
- To laugh
- To understand the logic behind the scenes
[] == [] // false
[] == ![] // true
Array is not an Array
The abstract equality operator converts both sides to numbers to compare them, and both sides become the number 0 for different reasons.
Explanation
+[] == +![]
0 == +false
0 == 0
true + true
// 2
Math is weird
When the plus operator is placed between two booleans, the booleans are converted to numbers
Explanation
Number(true) + Number(true)
1 + 1
parseInt("f*ck"); // -> NaN
parseInt("f*ck", 16); // -> 15
parseInt is a bad guy
This happens because parseInt will continue parsing character-by-character until it hits a character it doesn't know. The 'f' in 'f*ck' is the hexadecimal digit 15. By default radix is 10 (decimal)
Explanation
999999999999999 // -> 999999999999999
9999999999999999 // -> 10000000000000000
10000000000000000;// -> 10000000000000000
10000000000000000 + 1 // -> 10000000000000000
10000000000000000 + 1.1 // -> 10000000000000002
Magically increasing numbers
This is caused by IEEE 754-2008 standard for Binary Floating-Point Arithmetic. At this scale, it rounds to the nearest even number.
Explanation
1 < 2 < 3 // true
3 > 2 > 1 // false
Comparison knows some jokes
Explanation
1 < 2 < 3
true < 3
1 < 3 // true
3 > 2 > 1
true > 1
1 > 1 // false
Math.min(1, 4, 7, 2); // 1
Math.max(1, 4, 7, 2); // 7
Math.min() > Math.max(); // true
Math.max() less than Math.min()
Explanation
Math.min(); // Infinity
Math.max(); // -Infinity
null == 0; // false
null > 0; // false
null >= 0; // true
Comparing null to 0
Explanation
null == 0 // false
If you have null on one side of the equal sign, the other side must be null or undefined for the expression to return true. Since this is not the case, false is returned.
null > 0 // false
The algorithm here, unlike that of the abstract equality operator, will convert null to a number.
0 > 0 // false
The >= operator in fact works in a very different way, which is basically to take the opposite of the < operator.
null >= 0
!(null < 0)
!(0 < 0)
!(false)
[] + {} // "[object Object]"
{} + [] // 0
Funny math
From transposition of elements a sum does not change
Or does it?
Explanation
{} + []
+[] // 0
[] + {}
[].toString() + ({}).toString()
'' + "[object Object]" // "[object Object]"
{} parsed as empty block expresion
1 + {} // "1[object Object]"
{} + 1 // 1
Funny math v2
('b' + 'a' + + 'tman').toUpperCase()
// "BANAN"
Batman is not a Hero he used to be
Explanation
('b' + 'a' + + 'tman').toUpperCase()
('ba' + (+ 'tman')).toUpperCase()
('ba' + NaN).toUpperCase()
('ba' + 'NaN').toUpperCase() // BANAN
Thanks for attention
Resourses and Credits
Contacts
Skype: yavorco
Email: roman.yavoriv@techmagic.co
JS WAT
By Roman Yavoriv
JS WAT
Surprising parts of JavaScript
- 334