Skip to main content

Command Palette

Search for a command to run...

Difference between null and undefined (explained in 5 seconds)

Updated
1 min read

null says

there is absolutely nothing.

undefined says

there should be something but I have nothing.

This is why the following function returns undefined when the argument is passed nothing because it means the function needs something but it has nothing.

function foo(bar){
    return bar;
}
console.log(foo()); // undefined

Brainteaser: So, if you query a filtered list of Person from database and there is no Person data. What should function return null or undefined?

44 views
P

undefined means a variable has been declared but has not yet been assigned a value.

var TestVar;
alert(TestVar); //shows undefined
alert(typeof TestVar); //shows undefined

null is an assignment value. It can be assigned to a variable as a representation of no value.

var TestVar = null;
alert(TestVar); //shows null
alert(typeof TestVar); //shows object

From the preceding examples, it is clear that undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.

1
Difference between null and undefined (explained in 5 seconds)