JavaScript Null
Last Updated : 2 Mar 2025
What is Null in JavaScript?
In JavaScript, null is a value that represents the intentional absence of any object value. It is technically a primitive type, although in some cases, it behaves as an object.
In other words, null indicates the delibrate absence of any object value. It's a primitive value that denotes the absence of a value or serves as a particular for an object that isn't present.
There is a difference between the null and undefined that signifies a variable that has been declared but hasn't been assigned a value.
Syntax
The syntax of null in JavaScript is as follows:
Use Cases of Null in JavaScript
Object initialization
In JavaScript, when an object can't be created, it will return null, which is a common result:
Output:
Square { length: 10 }
null
Checking for null
In JavaScript, use null to indicate that a value is intentionally absent:
Output:
How to Check for Null in JavaScript
In JavaScript, if you want to check for null, then the simplest way to check is to know that null evaluates to false in conditionals or if coerced to a Boolean value:
Double Equality operator
In JavaScript, we have one way to check for null in JavaScript is to check if a value is loosely equal to null using the double equality == operator.
Example
It can be useful for checking for the absence of value: null and undefined both indicate an absence of value and are loosely equal, which means they have the same value even though they are different types.
In programming, it is crucial to always check if a variable has a value before attempting to process it. Use the ==null to check for either null or undefined.
Triple Equality Operator ===
In JavaScript, to make sure we have exactly a null value excluding any undefined values we need to use the triple equality === operator, otherwise known as the strict equality operators.
Example
So generally, it's a good idea to catch both null and undefined values as both represent an absence of a value.
It means checking for null is one of the few times in JavaScript that using == is recommended. Otherwise, you can also use the triple equality === operator.
Using the object.is() Function
In JavaScript, the object.is() function helps us to compare two values to see whether they are the same. A Boolean value indicates if the two parameters in the function have the same value. In this two values could be the same if both the values are null.
Syntax
Parameters
q: variable to be passed inside the function which is initialized with a null value.
Null: this parameter is a null value.
Algorithm
Step1: we declare a variable called q and set it to null.
Step 2: after than, we given the input q and a null value, we check the object.is() a method with an if-statement to determine whether both are the same.