Reputation: 2105
Context:
I'm trying to make sure that an object passed to a function is valid before I use it. And I'd like to know if there is any difference between the two approaches, one is more syntactically verbose than the other. If the functionality and behaviors are the same across all JavaScript engines used by modern user agents such Chrome, IE, FF etc., I'd rather use the simpler version. If not, I'd like to use the safe bet so my code behaves as I intended regardless of the JavaScript engine's implementation.
Question:
Given the following function, there are two statements as denoted by comment section.
Does statement 1 yield the same result as statement 2 regardless of the JS engine (or user agents)? And why or why not?
function f(obj) {
if(obj) { // statement 1
console.log('obj is valid');
}
if(obj !== null && obj!==undefined) { // statement 2
console.log('obj is invalid');
}
}
Upvotes: 2
Views: 114
Reputation: 187134
No, they are different.
if (obj)
tests for truthy values. In JavaScript everything is truthy except for ""
, 0
, false
, NaN
, null
and undefined
(there may be a few more I'm forgetting...)
But what if one of those falsy value is a value you are ok with, such as zero or false
? A quantity
of zero is a perfectly legit value, as is false
for isTotallyLame
. So you need a test that allows those values to pass. You need to test for existence.
if (obj!==null && obj!==undefined)
tests for existence. Only null
or undefined
will fail the test. This means that empty string ""
, zero 0
, or even false
are valid values because they are a set value.
However, as @Tim notes, the preferred standard test for existence looks like this:
if (typeof obj !== "undefined" && obj !== null)
Upvotes: 6