if (data !== null) vs if (data)
2024
- Checking explicitly if a value is
null
(orundefined
). - Checking for truthiness (falsy/truthy values).
1. if (data !== null)
vs if (data)
if (data !== null)
(Explicit null
Check)
In JavaScript, if you want to check explicitly whether a value is not null
, you can use the !==
operator. You can also check for both null
and undefined
using data != null
(which works for both).
Example:
let data = 0; // or false, '', [], {}, null, undefined, etc.
if (data !== null) {
console.log("Data is not null");
}
- This condition will evaluate to
true
ifdata
is anything exceptnull
. It will allow values like0
,false
,""
(empty string),[]
, and others.
To check for both null
and undefined
(which are often treated similarly in JavaScript), you can use:
if (data != null) {
console.log("Data is neither null nor undefined");
}
his will evaluate to true
as long as data
is not null
and not undefined
.
if (data)
(Truthiness Check)
In JavaScript, if (data)
checks for truthiness. This will evaluate to false
for falsy values like:
false
0
null
undefined
""
(empty string)NaN
(Not-a-Number)[]
and{}
(empty objects/arrays) are considered truthy in JavaScript, unlike Python.
Example:
let data = 0; // or false, '', [], {}, null, undefined, NaN
if (data) {
console.log("Data is truthy");
} else {
console.log("Data is falsy");
}
- In this case,
data = 0
will make the conditionfalse
because0
is considered a “falsy” value in JavaScript.
Key Differences:
if (data !== null)
orif (data != null)
: This is explicit. It checks if the value is notnull
(and optionally, notundefined
with!=
).if (data)
: This checks for truthiness. It will evaluate tofalse
for any “falsy” values likefalse
,0
,null
,undefined
,NaN
, or an empty string (""
). However, empty arrays ([]
) and empty objects ({}
) are considered truthy.
Summary:
- Use
if (data !== null)
when you need to ensure that the variable is notnull
, allowing other “falsy” values like0
,false
, and""
. - Use
if (data)
to perform a truthy check, meaning that any “falsy” value (likenull
,undefined
,false
,0
,""
, etc.) will be treated asfalse
.