Funny Side of JavaScript: Part One.
In this article, you’ll see few moments where JavaScript behaves in a weird way. After all, JavaScript is well known to be a funny and tricky language. It can become the most unpredictable thing ever at times. Let’s just jump right in and see how weird JavaScript can get and how it can easily leave us pulling out our hair with these ridiculous behaviours.
- NaN (Not a Number) is a number.
If you know JavaScript, you should know NaN. NaN is a variable in global scope which stands for ‘Not a Number’. Well, technically its type is number according to JavaScript which can be quite confusing for beginners.
How can something be a number and not a number at the same time? Guess that’s the million-dollar question. :)
typeof NaN; //returns 'number'
2. Math.min() is greater than Math.max().
Math.min() > Math.max(); //returns true
This seems ridiculous but if you de-structure each side and look at its values then it starts to make sense.
Math.min(); //this returns Infinity
Math.max(); //this returns -Infinity
Infinity > -Infinity; //returns true
3. Array.prototype.sort() might not give what you expect!
You might be confident that you can use sort() to sort an Integer array and yield the results you expect. Well, that’s where JavaScript decides to play its tricks. Have a look.
[140000, 104, 99].sort(); //returns [104, 140000, 99]
Rather than sorting the array in ascending order considering the number as a single unit, JavaScript has clearly decided to sort based off on the first digit (just like how strings are being sorted). If you’re wondering how to get the proper ascending order, consider adopting the following approach by passing a comparator function.
var arr = [140000, 104, 99];
arr.sort(function(a, b) {
return a - b;
});
4. ‘Boolean Math’. Oh Boy!
Consider the following example,
(true + true + true) * (true + true) + true; //returns 7
Looks weird? Well, this one is easy to guess. ‘true’ is truthy and so does 1. So, ‘true’ will be coerced to 1 and then it’s a simple arithmetic expression to solve which will result in 7.
5. NaN is not NaN
NaN === NaN; //returns false
Although both sides of NaN === NaN
contain the same value and their type is of type ‘Number’, they’re not the same. If one side is NaN with respect to strict equality operator, final result will be false according to ECMA-262 specifications. You can read more about this here .
Well, that’s all for this article. Hope you enjoyed reading it. Stay tuned for the second part. See you next time!