Here you will learn what is null and undefined in JavaScript and what is the difference between them.
What is a null?
A null means the absence of a value. You assign a null to a variable with the intention that currently this variable does not have any value but it will have later on. It is like a placeholder for a value. The type of null is the object.

Sometimes, null variables are the result of erroneous code. For example, if you try to find an HTML element using document.getElelementByID() with the wrong id, then it will return null. So it is recommended to check for null before doing something with that element.

What is undefined?
A variable is undefined when you haven't assigned any value yet, not even a null.

Generally, variables are undefined when you forgot to assign values or change existing code. For example, consider the following Greet() function that returns a string.

Thus, undefined variables are the result of some code problems.
Difference between null and undefined
You must explicitly assign a null to a variable. A variable has undefined when no value assigned to it.

The '' is not the same as null or undefined.

The type of null variable is object whereas the type of undefined variable is "undefined".

Use the === operator to check whether a variable is null or undefined. The == operator gives the wrong result.

The null and undefined variables are falsy to if-statements and ternary operators.

A null variable treated as 0 in an numeric expression whereas undefined variable will be NaN.

It will give wrong result when concatenated with string.

Note: The null and undefined variables are one of the main reasons for runtime errors in JavaScript. The best practice is to check variables for null or undefined before using them.
Top comments (0)