Javascript, The weird parts— Part 1
Javascript tries to do the best possible thing that it can rather than just throwing errors everywhere
People often say JS is confusing because it can evaluate nearly anything and the evaluation might not make sense. Below are few of the things that confuse people majorly.
Define constructors with an arrow function
let f = function() {
this.number = 10;
};
new f(); // -> { 'number': 10 }
Doing the same thing with an arrow function
let f = () => {
this.number = 10;
};
new f(); // -> TypeError: f is not a constructor
Arrow functions have lexical this
, and do not have a prototype
property, so new
cannot be called on it. Comparison of three numbers
1 < 2 < 3; // -> true
3 > 2 > 1; // -> false1 < 2 < 3; // 1 < 2 -> true
true < 3; // true -> 1
1 < 3; // -> true3 > 2 > 1; // 3 > 2 -> true
true > 1; // true -> 1
1 > 1; // -> false
Number.MIN_VALUE
is the smallest number, which is greater than zero:
Number.MIN_VALUE > 0; // -> true
Strings aren’t instances of String
"abc"; // 'str'
typeof "abc"; // 'string'
"abc" instanceof String; // false
Object as a key of an object’s property
{ [{}]: {} } // -> { '[object Object]': {} }
The object as a key gets evaluated to a string, so we get the property key '[object Object]'
and the value {}
.
Array.prototype.sort()
[ 10, 1, 5].sort() // -> [ 1, 10, 5]
The default sort order is built upon converting the elements into strings, then comparing their sequences of UTF-16 code unit values.
You should write a comparator function to make it work fine.
Something like this
[10, 1, 5].sort((a,b)=> a-b)
[] == ![]
How can something be equal to a negation of the same thing?
So ![] is evaluated to false
When false is compared to an array(an object), both get converted to numbers
[] gets converted to 0 and so does false. Hence they become equal