Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is empty string treated as falsy in javascript?

Tags:

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.

like image 262
AgentRegEdit Avatar asked Jun 13 '26 15:06

AgentRegEdit


1 Answers

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)

like image 148
Bergi Avatar answered Jun 15 '26 05:06

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!