Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 233
Hamster Avatar asked Oct 08 '10 04:10

Hamster


People also ask

Does an empty string equal 0?

An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .

How do you check if a string is not null?

To check if a string is null or empty in Java, use the == operator. Let's say we have the following strings. String myStr1 = "Jack Sparrow"; String myStr2 = ""; Let us check both the strings now whether they are null or empty.

How do you check if a value is empty or not?

Use the length property to check if a string is empty, e.g. if (str. length === 0) {} . If the string's length is equal to 0 , then it's empty, otherwise it isn't empty. Copied!

Is null or zero JavaScript?

The falsy values in JavaScript are null , undefined , false , 0 , "" (empty string), NaN (not a number). If the val variable stores a null value, the expression before the question mark returns true , and the ternary operator returns 0 .


2 Answers

If you want to detect all falsey values except zero:

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

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

like image 91
Quentin Avatar answered Oct 17 '22 01:10

Quentin


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.

like image 42
BoltClock Avatar answered Oct 17 '22 01:10

BoltClock