JPS
JPS

Reputation: 2760

Which way should be used for null comparison in JavaScript

To check whether an object is null or not in javascript, i have seen two ways,

let obj = {};

Option 1

if(obj){ console.log('object exists'); }

Option 2

if(!!obj === true){ console.log('object exists'); }

Is there any advantage of choosing one option over the other? which option is preferred as the standard code ?

Upvotes: 0

Views: 93

Answers (5)

traktor
traktor

Reputation: 19301

To test if a value obj is of Object data type, try

if( obj and typeof obj === "object") {
     // obj is an object and it's safe to access properties
}

The truthiness of obj indicates it's not null, and typeof returning "object" means it's not some other primitive data type.

Note that null is its own data type in JavaScript (null), but typeof null returns "object" because of limitations in the early implementations of the language.

Conversely, to test if a value is null and not an object, simply use a strict equality test:

if( obj === null) {
   // the data type of obj is null
   ...
}

Upvotes: 0

Parama Kar
Parama Kar

Reputation: 464

An object in javascript is always truthy irrespective of whether it has any property defined on it.

Thus,

var obj={}
if(obj){
//this block will always be executed.
}

If you want to check if an object has been defined in the current lexical scope try:

if(typeof(obj) !== 'undefined' && obj !== null){ 
  console.log('object exists'); 
}
else{
  console.log('nope')
}

If you want to check if an object has any property on it or it is an empty object try:

if(typeof(obj) !== 'undefined' && obj !== null){ 
  console.log('object exists'); 
}
else{
  if(Object.keys(obj).length){
    //do something
  }
}

Upvotes: 1

CodeYute
CodeYute

Reputation: 74

Choosing a comparison method varies on how you predict how the data type will be, but if you want a really safe standard, use 'typeof'. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

if( typeof obj === "object" ){ console.log('object exists'); }

if( typeof obj !== "undefined" ){ console.log('object exists'); }

Upvotes: -3

UtkarshPramodGupta
UtkarshPramodGupta

Reputation: 8152

Use simple ===.

In your code, you are not checking if the object is null or not. Instead, your code just checks if it's not a Falsy value. Note that there are a total of 6 Falsy Values in JavaScript, null being one of those. Read more about them here. If you just want to check if a variable is null, the following is the best way to go:

if (obj === null) { 
  console.log("object is null");
} else {
  console.log("object is not null");
}

Upvotes: 3

jh314
jh314

Reputation: 27792

If you only want to check if the object is null:

if(obj === null) {
...
}

Upvotes: 2

Related Questions