How do I NOT detect 0, but otherwise detect null or empty strings?
views:
145answers:
3
+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
2010-10-08 05:01:16
Oh so an empty string is the same as 0 with ==? Odd. Thanks!
Hamster
2010-10-08 05:09:18
Yes; in fact, that's one of the biggest reasons to prefer `===` over `==`. Due to automatic conversion, `false == 0 == ""`, but `false !== 0 !== ""`.
Amber
2010-10-08 05:11:03
Good, good +1. Would a better word for *translated* be *coerced*? (just thinking aloud) :)
alex
2010-10-08 05:17:38
@alex: Yes, it would. Thanks :)
BoltClock
2010-10-08 05:22:35
@BoltClock - Thanks for the refresher in this question. I had forgotten that "" was considered "falsey." +1
JasCav
2010-10-08 05:25:07
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
2010-10-08 06:23:20
@CMS: Ah, OK — looks like I got carried away then. Thanks for the correction.
BoltClock
2010-10-08 06:31:25
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
2010-10-08 05:08:04
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
2010-10-11 12:22:34