1. Introduction
null in JavaScript is an object which represents the intentional absence of value. null is a primitive value in JavaScript. null is treated as falsy for boolean operations.
null is different from undefined which also means absence of value. Variables which are declared but not assigned any value are initialized to default value of undefined. When a variable is assigned null, it is intentional as we are explicitly assigning value to it.
Let us understand this with an example.
var x = new String();
Here, x is referring to the object of string. When we assign null to x, i.e.
var x = null;
It means x is not referring to any object.
2. typeof with null
typeof operator returns object when used with null. null is an object in JavaScript.
console.log(typeof null); // object
3. Comparison of null
null will return true with both standard equality operator(==) and strict equality operator(===).
console.log(null == null); //true console.log(null === null); //true
4. null is not equivalent to undefined
null is intentional absence of value and is not equivalent to undefined.
console.log(null === undefined); //false
However, using standard equality operator (==) to compare null with undefined will return true.
console.log(null == undefined); //true
5. Coercion
null gets coerced to the number 0 when used with mathematical operator with numbers. null gets coerced to string null when used with strings. So you should be careful while using null with operators.
console.log(null + null); //0
console.log(1 + null); //1
console.log("1" + null); //1null
However, while using in boolean operations, null is treated as falsy.
console.log(null == 0); // false console.log(null === 0); // false
6. Conclusion
In this tutorial, we discussed null in JavaScript. Knowledge of null and its usage in comparison is very important. null and undefined code snippets are very important from interview point of view. Understanding of null is very important in writing boolean operations which are a part of almost every program.
We hope this tutorial was informative.
