The Weird Side of JavaScript Explained - ...

The Weird Side of JavaScript Explained - Part 1

Jan 29, 2024

JavaScript has unique behaviours that can be puzzling. Let's go through some of them with examples to understand better.

1. Arrays Equal Strings

In JavaScript, comparing an array to a string using the equality operator (==) can lead to unexpected results:
When comparing a or b with c, JavaScript converts the arrays to strings, resulting in a comparison of '0,1,2' == '0,1,2', which is true. However, when comparing a and b, it checks for object reference equality, and since a and b refer to different arrays in memory, the result is false.

2. Numbers Are Sorted Alphabetically

JavaScript’s default sort method converts numbers to strings and sorts them lexicographically (alphabetically):

3. String Is Not a String

The typeof operator can be misleading when used with strings:

The typeof operator returns 'string' for string literals. However, instanceof checks for an instance of the String object wrapper, which is not the same as a string literal.

4. Null Comparisons

Comparing null can yield unintuitive results:

In relational comparisons, null is treated like 0. However, with non-strict equality (==), null is only equal to undefined and no other value.

Part 2:

Original post:

Enjoy this post?

Buy Codecrumbs a coffee

More from Codecrumbs