What is null?
- The null value in javascript represents a non-existent or empty value.
- Null must be assigned.
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.
//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.
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.
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.
//output: false
console.log(Boolean(undefined))
- You can also assign undefined value to a variable explicitly.
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.
var newVar = undefined;
//output: true
console.log(typeof(newVar) === 'undefined');
Operations between null and undefined
//"object" (for legacy reasons)
typeof null
//"undefined"
typeof undefined
//false as both are of different types
null === undefined
//true
null == undefined