null vs undefined

Mateusz -

Telling the differences between null and undefined can be tricky. Testing these with if statements will give us the same result, false. What’s the difference between one and the other?

null

Something set on purpose to say that there is nothing there.
It means just nothing, emptiness.
Type of null is object.
Indicates the absence of a value.

We can use null as a value when we want to create a new variable and just not use it at the beginning. For example we want to use it later in our code, but we need to have the variable already created.

undefined

Something that does not have a value, but it's container exists.
Type of undefined is undefined.
Indicates absence of variable itself.
//
var name;

console.log(name); //undefined

function sayHello() {
  //if function body will be empty then function will return undefined
}

sayHello(); //undefined

Console logs in action with null and undefined

Below you will find examples of the use and comparison of null and undefined.

//
console.log(typeof null); //object
console.log(typeof undefined); //undefined

console.log(!undefined); //true
console.log(!null); //true

console.log(undefined == undefined); //true
console.log(undefined === undefined); //true

console.log(null == null); //true
console.log(null === null); //true

console.log(null == undefined); //true
console.log(null === undefined); //false
//

The last two cases are interesting. When we compare null to undefined with == it will compare only the value, and the value will be false for both null and undefined. But when we compare null to undefined with === (it also compares the type) then the result will be false because type of null is an object and type of undefined is undefined.