Difference between undefined and null in JavaScript

bishnucit

Bishnu Prasad Chowdhury

Posted on February 4, 2021

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.

💖 💪 🙅 🚩
bishnucit
Bishnu Prasad Chowdhury

Posted on February 4, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related