I\'ve noticed that if you have a statement as the following:
var test = \"\" || null
test
will evaluate to null
b
One dangerous issue of falsey values you have to be aware of is when checking the presence of a certain property.
Suppose you want to test for the availability of a new property; when this property can actually have a value of 0 or "", you can't simply check for its availability using
if (!someObject.someProperty)
/* incorrectly assume that someProperty is unavailable */
In this case, you must check for it being really present or not:
if (typeof someObject.someProperty == "undefined")
/* now it's really not available */
SEE HERE
Yes an empty string is falsy, however new String("")
is not.
Note also that it's well possible that
if (x) { ... }
is verified, but that
if (x == false) { ... }
is verified too (this happens for example with an empty array []
or with new String("")
).
Does javascript treat empty string as either a falsy or null value, and if so why?
Yes it does, and because the spec says so (§9.2).
Isn't an empty string still an object
No. An primitive string value is no object, only a new String("")
would be (and would be truthy)
A string isn't an object in JS. Other "falsy" values are: 0
, NaN
, null
, undefined
.
String is not an object, it's a primitive like number or boolean.
The empty string, NaN, +0, -0, false, undefined and null are the only values which evaluate to false in direct boolean conversion.