views:

145

answers:

3

How do I NOT detect 0, but otherwise detect null or empty strings?

+9  A: 

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.

BoltClock
Oh so an empty string is the same as 0 with ==? Odd. Thanks!
Hamster
Yes; in fact, that's one of the biggest reasons to prefer `===` over `==`. Due to automatic conversion, `false == 0 == ""`, but `false !== 0 !== ""`.
Amber
Good, good +1. Would a better word for *translated* be *coerced*? (just thinking aloud) :)
alex
@alex: Yes, it would. Thanks :)
BoltClock
@BoltClock - Thanks for the refresher in this question. I had forgotten that "" was considered "falsey." +1
JasCav
Actually, `0 == ""` doesn't *coerce* to `false == false`, at the end the compared values will be: `0 == 0`. That happens because if one of the operands of the Equals Operator is a Number value, the other will be also converted to Number, and an empty or whitespace only string, type-converts to `0`, e.g.: `+""` or `Number("")`. Another example: `0 == { valueOf:function () { return 0;} }` evaluates to `true`, because the object defines an own `valueOf` method, which is used internally by the `ToNumber` operation, and we know it doesn't *coerce* to `false`, because an object is **never** *falsy*.
CMS
@CMS: Ah, OK — looks like I got carried away then. Thanks for the correction.
BoltClock
A: 

If I understood correctly, you wanted to detect a non empty string?

function isNonEmptyString(val) {
  return (typeof val == 'string' && val!='');
}
/*
  isNonEmptyString(0); // returns false
  isNonEmptyString(""); // returns false
  isNonEmptyString(null); // returns false
  isNonEmptyString("something"); // returns true
*/
ArtBIT
A: 

If you want to detect all falsey values except zero:

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

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

David Dorward