What is null?
- The null value in javascript represents a non-existent or empty value.
- Null must be assigned.
1 2 3
let a = null; //output: null console.log(a);
- Null is one of the falsy values in javascript. It means it is treated as false in any boolean operation in javascript.
1 2
//output: false console.log(Boolean(null))
- If you check the type of null using typeof operator, it will return the object. It is a bug in Javascript code and hasn't been removed because a lot of libraries and code depends on it.
1 2 3 4
let a = null; let nullType = typeof(a); //output: "object" console.log(nullType);
What is undefined?
- Undefined in javascript means that a variable has been declared, but no value is assigned to it.
1 2 3
let newVar; //output: "undefined" console.log(newVar);
- Undefined is also one of the falsy values in javascript. It means it is treated as false in any boolean operation in javascript.
1 2
//output: false console.log(Boolean(undefined))
- You can also assign undefined value to a variable explicitly.
1 2 3
var newVar = undefined; //output: false console.log(newVar);
typeof undefined in javascript is undefined. You can use typeof operator to check if a variable is undefined in javascript.
1 2 3
var newVar = undefined; //output: true console.log(typeof(newVar) === 'undefined');
Operations between null and undefined
1 2 3 4 5 6 7 8 9 10 11
//"object" (for legacy reasons) typeof null //"undefined" typeof undefined //false as both are of different types null === undefined //true null == undefined