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.

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; // -> false
1 < 2 < 3; // 1 < 2 -> true
true < 3; // true -> 1
1 < 3; // -> true
3 > 2 > 1; // 3 > 2 -> true
true > 1; // true -> 1
1 > 1; // -> false
Number.MIN_VALUE > 0; // -> true
"abc"; // 'str'
typeof "abc"; // 'string'
"abc" instanceof String; // false
{ [{}]: {} } // -> { '[object Object]': {} }

The object as a key gets evaluated to a string, so we get the property key '[object Object]' and the value {}.

[ 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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store