-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?

1
  • 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 is how truthy/falsey values work in JS. Commented Sep 20, 2016 at 16:59

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.