null and undefined in JavaScript


In JavaScript, null is a special value that represents an empty value.

let number = null;        

The code above suggests that the number variable is empty at the moment.

null is falsy

Besides false, 0, an empty string (''), undefined, NaN, null is a falsy value. It means that JavaScript will coerce null to false in conditionals.

const message = null;

if (message) {
console.log('No Messages');
} else {

// Output : "Message"        

In this example, the message variable is null therefore the if statement evaluates it to false and executes the statement in the else clause.

typeof null is object
console.log(typeof 25)      // Output : 'number'

console.log(typeof null);   // Output : ‘object’        

If a variable is declared but the value is not assigned, then the value of that variable will be undefined

let name;

console.log(name);    // Output : undefined        
typeof undefined is undefined
let name;

console.log(typeof(name));   // Output : ‘undefined’           
Null vs undefined

null is an assigned value. It means nothing.

undefined means a variable has been declared but not defined yet.

null is an object. undefined is of type undefined.

null !== undefined but null == undefined.

Posted in

Ankit Patel

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top