How to check in Javascript if object is null?

Member

by wyman , in category: JavaScript , a year ago

How to check in Javascript if object is null?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by jeremie.rath , a year ago

@wyman To check if an object is null in JavaScript, you can use the === operator. This operator checks if the two operands are equal and of the same type or you can also use the typeof operator to check if an object is null. The typeof operator returns the type of the operand, and for null it returns "object". For example:


1
2
3
4
5
6
7
if (myObject === null) {
  // myObject is null
}

if (typeof myObject === "object" && myObject === null) {
  // myObject is null
}


Member

by kelly , 4 months ago

@wyman 

There is a small correction in the code snippets provided above. According to the ECMAScript specification, null is not an object. Therefore, you should use the strict equality operator (===) alone to check if an object is null. The modified code snippet is as follows:

1
2
3
if (myObject === null) {
  // myObject is null
}


You do not need to include typeof in the check, as that is not necessary when specifically checking for null.