5

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.

AgentRegEdit
  • 1,089
  • 2
  • 16
  • 32

5 Answers5

12

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)

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Ah makes more sense now, thanks! It still seems like an odd decision to me to make empty string falsy, but I guess I have to get used to thinking of strings as a primitive type, instead of objects. – AgentRegEdit Apr 22 '13 at 11:31
0

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.

Esailija
  • 138,174
  • 23
  • 272
  • 326
0

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

Loamhoof
  • 8,293
  • 27
  • 30
0

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

Community
  • 1
  • 1
PSR
  • 39,804
  • 41
  • 111
  • 151
0

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

6502
  • 112,025
  • 15
  • 165
  • 265