In javascript, is an empty string always false as a boolean?

cc young picture cc young · Jan 1, 2012 · Viewed 88.6k times · Source

in javascript,

var a = '';
var b = (a) ? true : false;

var b will be set to false.

is this a defined behavior that can be relied upon?

Answer

Arenielle picture Arenielle · Jan 1, 2012

Yes. Javascript is a dialect of ECMAScript, and ECMAScript language specification clearly defines this behavior:

ToBoolean

The result is false if the argument is the empty String (its length is zero); otherwise the result is true

Quote taken from http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf