This if statement should not detect 0; only null or empty strings

42,807

Solution 1

From your question title:

if( val === null || val == "" )

I can only see that you forgot a = when attempting to strict-equality-compare val with the empty string:

if( val === null || val === "" )

Testing with Firebug:

>>> 0 === null || 0 == ""
true

>>> 0 === null || 0 === ""
false

EDIT: see CMS's comment instead for the explanation.

Solution 2

If you want to detect all falsey values except zero:

if (!foo && foo !== 0) 

So this will detect null, empty strings, false, undefined, etc.

Solution 3

function isNullOrEmptyString(val) {
  return (val === null || val === '');
}

console.log({
"isNullOrEmptyString(0)": isNullOrEmptyString(0), 
"isNullOrEmptyString('')": isNullOrEmptyString(""), 
"isNullOrEmptyString(null)": isNullOrEmptyString(null),
"isNullOrEmptyString('something')": isNullOrEmptyString("something"),
});

Share:
42,807
Hamster
Author by

Hamster

Updated on April 23, 2020

Comments

  • Hamster
    Hamster about 4 years

    Using JavaScript, how do I NOT detect 0, but otherwise detect null or empty strings?