Gopi Krishna
Published on

Null vs Undefined in JavaScript in 1 min

title

I always had a slight 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

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

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

let userDetails = null;

Later we assign 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 that 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.

Reference