DEV Community

 Bishnu Prasad Chowdhury
Bishnu Prasad Chowdhury

Posted on

Difference between undefined and null in JavaScript

Undefined is set by javascript automatically when a value of a variable is defined but value is not set or not declared at all.

Null is an empty object which is set by the programmer to reset a value of a variable.

If undefined is passed to a function as argument it does not over write the default value where as null does. If function parameter is not passed it is undefined.

let a = {};
> undefined

let b = function (a=true){console.log(a);}

b(null);
> null

b(undefined);
> true

function c(a,b){ console.log(a,b);}
c(null, 5);
> 5

Enter fullscreen mode Exit fullscreen mode

Null is an empty object type and undefined is of type undefined.

typeof(undefined);
> undefined

typeof(null);
> object

Enter fullscreen mode Exit fullscreen mode

Null means nothing and undefined means not defined hence both can mean false.

null == undefined;
> true

null === undefined;
> false

Enter fullscreen mode Exit fullscreen mode

Undefined is not valid in JSON but null is valid.

Adding undefined with a number result to NaN where as null gives the same number.

let a = 5 + undefined
a
> NaN

let b = 6 + null
b
> 6

Enter fullscreen mode Exit fullscreen mode

Finally both null and undefined usage should be avoided. We do have optional chaining that can help avoid using null.

Top comments (1)

Collapse
 
fredymorales83 profile image
Edwin Fredy Morales Morales

just I started learning JS, this topic is important to difference this points that causes confusion