AgentRegEdit
AgentRegEdit

Reputation: 1109

Is empty string treated as falsy in javascript?

I've noticed that if you have a statement as the following:

var test = "" || null

test will evaluate to null but if we do something like the following:

var test = "test" || null

test will evaluate to "test", the same holds true for any object in place of the string, so does javascript treat empty string as either a falsy or null value, and if so why? Isn't an empty string still an object, so shouldn't it be handled the same?

I've tested this out in FireFox, Chrome, IE7/8/9, and Node.

Upvotes: 6

Views: 9995

Answers (5)

6502
6502

Reputation: 114481

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("")).

Upvotes: 1

PSR
PSR

Reputation: 40318

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

Upvotes: 0

Loamhoof
Loamhoof

Reputation: 8293

A string isn't an object in JS. Other "falsy" values are: 0, NaN, null, undefined.

Upvotes: 0

Bergi
Bergi

Reputation: 664395

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)

Upvotes: 12

Esailija
Esailija

Reputation: 140210

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.

Upvotes: 0

Related Questions