-1

I think in every language I know

if(a)

is the same thing as

if(a == true)

Turns out in JavaScript it isn't true, because:

if([])

Seems to act as if the condition is fulfilled, but:

if([] == true)

Does the opposite thing.

I can't really find any possible explanation, especially that this problem doesn't occur with empty string for example (which is == true, but isn't === true, same as empty array). Is this a bug in JavaScript or what?

Aᴍɪʀ
  • 7,623
  • 3
  • 38
  • 52
  • 1
    `if(a) [...] same as [...] if(a == true)` - erm, that might just be PHP and maybe Python? It's not nearly universal to be able to convert an arbitrary value into a boolean. At any rate, [here](http://dorey.github.io/JavaScript-Equality-Table/) is how truthy/falsey values work in JS. – VLAZ Sep 20 '16 at 16:59

1 Answers1

2

In JavaScript, there is a concept of truthy and falsey values. if statements test the truthiness or falsiness of a given value rather than strict equality to true or false.

true is obviously truthy. false is obviously falsey. The rest can be a little tricky. MDN has possibly the clearest documentation about which values evaluate to falsey: https://developer.mozilla.org/en-US/docs/Glossary/Truthy

In this case [] is a truthy value so the condition passes and the code is executed.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536