174

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?

PhoneixS
  • 10,574
  • 6
  • 57
  • 73
cc young
  • 18,939
  • 31
  • 90
  • 148
  • Are you sure, I am getting `false` here: http://jsfiddle.net/8CKbd/ – anubhava Jan 01 '12 at 12:04
  • I took it a step further. String with spaces is true. if (' ') {console.log('!')} but the ' ' == 0 is true. – Azat Apr 30 '15 at 18:13
  • 2
    I think that @JonH edition is wrong, the empty string `''` is evaluated to false in a boolean context so if `a = '';` then `a ? false : true` => `'' ? false : true` => `false ? false : true` => `true` ( because is the evaluation for a false value). I think it should be `var b = (a) ? true : false;` to be correct with the next statement. – PhoneixS May 09 '19 at 16:19
  • @PhoneixS edited, hope it's more meaningful now. – SwissCoder Jun 05 '20 at 15:09
  • 1
    @SwissCoder it wasn't that is not readable but that it outputs another answer. Now I have corrected it. – PhoneixS Jun 08 '20 at 07:04
  • @PhoneixS perfect! sorry had gotten confused myself while editing :D – SwissCoder Jun 15 '20 at 07:06

6 Answers6

247

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

Community
  • 1
  • 1
Arenielle
  • 2,737
  • 1
  • 15
  • 7
  • 1
    Aaaaand it's settled – Anthony Mar 02 '16 at 22:34
  • 48
    One caveat is that `new String("")` is truthy! This is because it is an object, whereas the short form `""` represents the primitive value version. The same goes for `new Number(0)` and even `new Boolean(false)`. It's a good reason not to use the object versions in your code, and it does mean that `if (str.length)` handles this edge case whereas `if (str)` would not. – Chris Middleton Sep 17 '16 at 01:55
67

Yes. All false, 0, empty strings '' and "", NaN, undefined, and null are always evaluated as false; everything else is true.

And in your example, b is false after evaluation. (I think you mistakenly wrote true)

Charles Burns
  • 10,310
  • 7
  • 64
  • 81
Hossein
  • 4,097
  • 2
  • 24
  • 46
  • 2
    `null` is not `false`, neither `true`, `null` is `null`. https://jsfiddle.net/sq1Lkpg0/ – Bruno Finger Jul 22 '15 at 11:54
  • 12
    @Bruno, You can perform the same test with `NaN` and `undefined`. They are not `false` but they are falsy. Which is what was asked. – Joseph Feb 25 '16 at 23:52
17

var a = '';
var b = (a) ? false : true;   // fixed!
console.log(b);               // => true

var b will be set to true.

is this a defined behavior that can be relied upon?

As answered above, yes, that is the defined behavior of an empty string in a conditional (an if expression, ||, &&, ? :, ...). (The standard says that the internal ToBoolean operation must be applied.)

The evaluation is different when the empty string is used in a comparison (see Truth, Equality and JavaScript), even though the results are mostly the same:

// conditional (note: evaluation to false prints false here!)
console.log('' ? true : false); // zero length     => false

// comparisons
console.log('' == true);        // +0 === 1        => false
console.log('' == false);       // +0 === +0       => true
console.log('' === true);       // different types => false
console.log('' === false);      // different types => false

Explanation: Essentially, when the operands of == have different types, JavaScript tries hard to convert them to Numbers, according to their value, (using operations the standard calls ToNumber and ToPrimitive), and then it internally applies ===. But when you use === directly, the types are not converted, so comparing a String to a Boolean is always false.

Roughly speaking, JavaScript conditionals (ToBoolean) test for a defined, non-null, non-zero, non-empty, non-false value (an empty String is ... empty, the Numbers -0 or +0 are ... zero, NaN is not a defined number, but an empty Object is apparently not really empty), or as I like to think, conditionals test for a (true) thing, while == compares the apparent, carefully converted values (ToPrimitive, ToNumber) of its operands, and === looks for exact sameness.

if (X) {}        // is X a (true) thing?
if (X == Y) {}   // are the values of X and Y same-ish?
if (X === Y) {}  // are X and Y exactly the same?

There are more examples in Truth, Equality and JavaScript where this distinction really matters, e.g. '0' is true in a conditional (non-zero length, or, it is a thing), but false in a == comparison (the value is zero). '1' again, is true in both cases (it is a thing and has a non-zero value).

console.log('' ? true : false);   // zero length     => false
console.log('' == true);          // +0 === 1        => false
console.log('0' ? true : false);  // non-zero length => true
console.log('0' == true);         // +0 === 1        => false
console.log('1' ? true : false);  // non-zero length => true
console.log('1' == true);         //  1 === 1        => true
Orafu
  • 311
  • 2
  • 5
  • 1
    At first I thought, "pssh, that's overkill, this was well-answered already." But that was well-presented and informative. Thanks. – Marc L. Jul 15 '17 at 02:24
9

var b will be set to true. This is because an empty string counts as a 'falsey' value in JavaScript as do some other values.

Please look at http://www.sitepoint.com/javascript-truthy-falsy/ for falsy values

Jonathon Bolster
  • 15,811
  • 3
  • 43
  • 46
5

Examples of expressions that can be converted to false are those that evaluate to null, 0, the empty string (""), or undefined. (see MDN Reference)

Marcel Jackwerth
  • 53,948
  • 9
  • 74
  • 88
3

Yes, you can rely on that behavior.

A shorter way to write it will be:

var b = !!a;
Jöcker
  • 5,281
  • 2
  • 38
  • 44