Gopi Krishna
Published on

Null vs Undefined in JavaScript in 1 min


I always had a small confusion between null and undefined in JavaScript.

Now, Let's dive into the topic.

When we declare a variable without assigning any value to it, its value will be undefined by default.

let color;
console.log(color); //undefined

But when we assign null to a variable, we are explicitly assigning a "nothing" or "empty" value to it.

For example, we have a userDetails variable which stores the details of an user. At first, it doesn't have any data, so we are assigning null to it.

let userDetails = null;

Later we fill the userDetails variable with the response from our function getUserDetails. The function may be a call to an API or accessing localStorage for details etc. Here it’s just a simple function which returns an object.

function getUserDetails() {
  return {
    userName: 'gk',
    id: '1',

userDetails = getUserDetails();
console.log(userDetails); // {userName:"gk", id:"1"}

If the value is unknown at the time of variable definition, it's always best to use null.

Thank you.


undefined - MDN | null - MDN

Javascript Grammer