null and undefined in JavaScript:

As we have seen in the variable section that we can assign any primitive or non-primitive type of value to a variable. JavaScript includes two additional primitive type values - null and undefined, that can be assigned to a variable that has special meaning.

null:

You can assign null to a variable to denote that currently that variable does not have any value but it will have later on. A null means absence of a value.

Example: null

var myVar = null;
alert(myVar); // null

In the above example, null is assigned to a variable myVar. It means we have defined a variable but have not assigned any value yet, so value is absence.

null is of object type e.g. typeof null will return "object"

If you try to find DOM element using document.getElelementByID for example, and if element is found then it will return null. So it is recommended to check for null before doing something with that element.

undefined:

Undefined is also a primitive value in JavaScript. A variable or an object has an undefined value when no value is assigned before using it. So you can say that undefined means lack of value or unknown value.

Example: undefined

var myVar;
alert(myVar); // undefined

undefined is a token. typeof undefined will return undefined not an object.

In the above example, we have not assigned any value to a variable named 'myVar'. A variable 'myVar' lacks a value. So it is undefined.

You will get undefined value when you call a non-existent property or method of an object.

null and undefined is one of the main reasons to produce a runtime error in the JavaScript application. This happens if you don't check the value of unknown return variables before using it. If you are not sure that a variable will always have some value, the best practice is to check the value of variables for null or undefined before using them.

Points to Remember :

null and undefined are primitive values in JavaScript.

A null value means absence.

An undefined value means lack of value.

A null or undefined value evalutes to false in conditional expression.