Null vs Undefined in JavaScript
In this tutorial, we will learn the basic differences between Null and Undefined in JavaScript.
The difference between NULL and Undefined is as follows:
NULL:
The null keyword in JavaScript specifies that a particular variable or object has not been assigned any value.
var num1 = null; var num2 = 3; console.log(num1) console.log(num2)
The output will be:
null 3
In other words, it can be said that:
- NULL is an empty non-existent value
- For any computation, it must be assigned with a value
- When a variable is assigned to null, its value is null.
- When a data type is assigned to null, the data type is an object
var a= null; var b= 3; var c= a+b; console.log(c);
Output:
3
var a= null; var b= 3; a=4; var c= a+b; console.log("sum is: ",c);
Output:
sum is: 7
Undefined:
Undefined is a JavaScript global variable that creates during runtime. It is created when:
- An object or variable is called but not defined.
- When array index out of bound is assigned a value
- When a variable is assigned to undefined, its value is undefined.
- When a variable is assigned to undefined, the data type is considered undefined
- Unlike null, undefined is not a reserved keyword in JavaScript
An undefined function parameter is called
var demo; console.log(demo)
The following code will show error and thus “Undefined” will be called.
Output:
undefined
One can also explicitly set a variable to be undefined as shown in the example below:
var c = undefined; console.log(c);
The above code will call “undefined”.
Output:
undefined
Also read: How to remove a particular element from Array in JavaScript
Leave a Reply