Difference between undefined and null in JavaScript
Bishnu Prasad Chowdhury
Posted on February 4, 2021
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
Null is an empty object type and undefined is of type undefined.
typeof(undefined);
> undefined
typeof(null);
> object
Null means nothing and undefined means not defined hence both can mean false.
null == undefined;
> true
null === undefined;
> false
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
Finally both null and undefined usage should be avoided. We do have optional chaining that can help avoid using null.
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
November 29, 2024