Reputation: 131
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
Reputation: 1266
They are not.
Any falsy value will pass the test: 0, -0, null, undefined, an empty string, false.
Upvotes: 0
Reputation: 12874
When you're using !
operator in checking, if compares all falsey
value
Below is the list of falsey
value:
In other words:
let obj = '';
if(!obj) { console.log('opps, not undefined, still printing')}
Upvotes: 1
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