Difference between null and undefined

Null and undefined both mean that there is no value for the variable that you are trying to access.

Only difference between null and undefined is the actual intent that the programmer is trying to show you by using the keyword null or undefined.

You’ll notice that nowhere at all inside javascript are you going to get the keyword null unless some programmer somewhere actually specifically returns the keyword null. It doesn’t just come up on its own in javascript, you are only going to find it if it’s specifically being returned as null.

So with using null you are explicitly saying – this thing has no value. You checked for this value or did some calculations and there is no value at all and you are returning null to tell someone that there is no value for this thing that you are looking for.

Example of this would be if you have a list of things and you’re trying to find something in that list, if it doesn’t exist – you return null.

Undefined on the other hand is not explicitly saying that there is no value, it is just saying – this thing hasn’t been defined yet.

Example:

let a;

console.log(a);
// undefined

When you first create variable a with let a; the value of a is going to be undefined until you actually define it and give it a value. So undefined is kind of like the default state of everything.

So by defining something with null, you are basically saying – this thing has been defined, but it does not have any value at all, while if something is undefined it is essentially saying – this thing is not defined yet.