Melissa93
Melissa93

Reputation: 131

simply checking of undefined and null using !obj

I know undefined is not === to null but how about ! operator? If I have a code that do this checking,

if (obj === undefined || obj === null)

is it wise to just simplify it as

if(!obj)

Are they identical?

Upvotes: 2

Views: 42

Answers (3)

Julien Bérubé
Julien Bérubé

Reputation: 1266

They are not.

Any falsy value will pass the test: 0, -0, null, undefined, an empty string, false.

Upvotes: 0

Isaac
Isaac

Reputation: 12874

When you're using ! operator in checking, if compares all falsey value

Below is the list of falsey value:

  • false
  • 0 and other forms of numeric zero like -0, 0.0 and 0x0 (credit to RBT for hex form)
  • "", '' and `` - strings of length 0
  • null
  • undefined
  • NaN
  • document.all

In other words:

let obj = '';

if(!obj) { console.log('opps, not undefined, still printing')}

Upvotes: 1

Neil Locketz
Neil Locketz

Reputation: 4318

No.

!obj is also true for falsy things like 0.

While obj === undefined || obj === null is only true if obj is null or undefined.

!obj is true for any falsy value.

They are:

  • false (not really 'falsy' per-se ...)
  • 0
  • ""
  • null
  • undefined
  • NaN

Upvotes: 1

Related Questions