DEV Community

Cover image for NULL vs UNDEFINED in JS
Manu Martinez
Manu Martinez

Posted on

NULL vs UNDEFINED in JS

The first main question that all JS developer should know, it can sound really confused but it's so easy to understand when you know whatever needed 😁.

Both of them looks the same, it indicates that this var/let/const hasn't have any value yet 😙, the difference is mainly that undefined indicates that you have NEVER give a value to this property, let's see a brief example:

let a;
console.log(a); // it'll print undefined
Enter fullscreen mode Exit fullscreen mode

It's really clear, if you look at the example, I'm sure you are seeing that a = is missing, then it means that you don't want to assign value therefore, it's undefined, 😅.
Imagine if you want to check if a value is undefined you can make this approach:

if (typeof a === 'undefined') {
  console.log(`Hey!! it's undefined');
}
Enter fullscreen mode Exit fullscreen mode

Moreover, you can declare a var an assign a value, but later during the execution you can change it to undefined:

let a = 10;
a = undefined;
console.log(a); // it'll print undefined
Enter fullscreen mode Exit fullscreen mode

Then you can say to JS that you have to change the var to non-assigned yet 👨🏼‍💻.
Differently, null indicated that var hasn't any value but it has been inited:

let a = null;
Enter fullscreen mode Exit fullscreen mode

It commonly used to indicate to JS that var won't be use more 🤝. The most curious detail is that both of them are false when you create a computation or when you try to check it using an if sentence, but what will happen if you try to compare undefined with null:

undefined == null
Enter fullscreen mode Exit fullscreen mode

Do you know what will it print?.
I recommend you to put this staff inside the bowser console to check the result, it will very useful to understand what these type mean.

This is mainly what JS has undefined and null values 🥰, then this is all for today post, I remind you that if you have any question you can ask me using comments here, it will be a pleasure to help you 🤑

Top comments (0)