Tricky JavaScript: Part-1

Pratik Das
3 min readMay 9, 2021

JavaScript is a very popular language. It is easy to learn and work with. Most web developers start their careers by learning JavaScript. Even after working with js for many years, JavaScript is able to trick you with one way another and it can make your life miserable.

So, today we are going to see a few such tricky examples which might help you for later and you can deep dive in and explore more such examples.

Array is equal not array:

const arr = []arr == !arr; // -> trueExplanation:
arr == 0 // -> true (empty array directly converted to 0)
!arr == false // -> false
false == 0 // -> true (0 represents false)

The equality operator converts both sides into numbers to compare them. both the side becomes 0 for different reasons.

On the left side, the empty array represents 0 without converting to boolean first.

On the right side, the opposite of the truthy array is false. which then is converted as 0.

Another Explanationconst arr = []
arr == !arr;
0 == +false;
0 == 0;
true;

true is false

!!"false" == !!"true"; // -> true
!!"false" === !!"true"; // -> true

Again for equality checking, we have to convert both the side into integers.

“true” and “false” is in string form which considers as NaN as we are converting both the sides to numbers.

!!"false"  // -> true
!!"true" // -> true

baNaNa

"b" + "a" + + "a" + "a" // -> "baNaNa"

After seeing this code it seems like the compiler should have given the error. but my friend it does not happens here.

The expression compiler read is:

"b" + "a" + (+"a") + "a" // +"a" is addition operation which converts as "NaN"

Yes, you saw it correctly. This is the reason you get “baNaNa” as your output.

Minimal value is greater than zero

JavaScript provides the variable “Number.MIN_VALUE” which returns the smallest number. but do you know it is still greater than zero

Number.MIN_VALUE > 0; // -> trueNumber.MIN_VALUE      // Value : 5e-324

The Number.MIN_VALUE returns the smallest positive number that is as close as you can get to zero but it is greater than zero.

Adding arrays

Have you before added two arrays with an addition operator??

[1, 2, 3] + [4, 5, 6];  //'1,2,34,5,6'

The reason is that it does not add to array index by index. What it does, it converts the array to string values.

This is how it works:

[1, 2, 3].toString(); //  '1,2,3'
[4, 5, 6].toString(); // '4,5,6'
[1, 2, 3].toString() + [4, 5, 6].toString();
'1,2,3' + '4,5,6' //'1,2,34,5,6'

Hope you find it useful and understand fundamental behind how the above examples work. There are plenty of such examples to share with you.

For now, this is it. There will be more examples in Part 2.

--

--