Null vs Undefined in JavaScript in 1 min

📅 23 July, 2019 | ☕️1 min read

I always had a small confusion between null and undefined in JavaScript. My confusion got cleared, after reading JS Grammar by @js_tut.

Checkout JS Grammer, It's an awesome resource to learn 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.

Reference

undefined - MDN | null - MDN

Javascript Grammer

Gopi Krishna

Hello, thanks for the read! If you found this article helpful, have constructive feedback, or just want to say hello, connect with me on social media or drop a comment below. Thanks in advance!