Did you know that about JavaScript?

A list of things I think are interesting to know

1. Null has a type of ‘object’

const val = null; typeof val;

// ‘object’

2. Array has a type of ‘object’

const arr = []; typeof arr;

// ‘object’

3. You can perform functions directly on a string.

const str = "Sunil".toUpperCase(); console.log(str)

// 'SUNIL'

4. Primitive values that are equal will always return true when compared with the triple equality operator

const num1 = 5

const num2 = 5 num1 === num2

// true

5. Even if you set it up like this…

const sun1 = "sun" + "il";

const sun2 = "su" + "n" + "il"; sun1 === sun2;

// true

6. This works for all primitive values, except for NaN

const momma = NaN;

const poppa = NaN; momma === poppa;

// false

7. Non-primitive values, such as arrays and objects, will not result in values that are not exactly equal

const x = { name: "Sunil Sandhu" };

const y = { name: "Sunil Sandhu" }; x === y;

// false

8. However, if you compare the properties inside…

const x = { name: "Sunil Sandhu" };

const y = { name: "Sunil Sandhu" }; x.name === y.name;

// true

9. Functions cannot mutate primitives

const func = (number) => {

number = number + 1;

} let val = 1; func(val); val;

// 1

10. But they can mutate properties inside of an non-primitive

const func = (number) => {

number.value = number.value + 1;

} let newNumber = {value: 1}; func(newNumber); newNumber;

// {value: 2}

11. That 5 + 5 = 10, but 5+ 5 + [] = “10”

This is because using + with an array will trigger string concatenation as an array has no inherit numerical value. Therefore, [].toString is implicitly called. Array.prototype.toString automatically calls Array.prototype.join to join all the array values into a single string. [].join() will join an empty array, so the result is "" , so [].toString() is also "" .

5 + "" will result in the string "5" because an empty string is added to a number, so the number is also converted to a string.

12. And just to make matters worse…

[] + 3 + 3 === “33”

And there we have it!

Some stuff that I thought was worthwhile mentioning. I will likely use this as a hub for adding more interesting things as I come across them, so be sure to bookmark this and check back from time to time. Likewise, if you have noticed anything interesting in JavaScript, be sure to leave a message in the comments and maybe we will get yours added!

Sources

11, 12: Source