re: JavaScript Quiz VIEW POST


One of my favorite web-slinger questions (for fun, not for job interviews) is: can you name all 8 of the falsy things?

Here's the first falsy thing, to get you started, which is pretty much a gimme:

  • false

I'm out. What are the last 2?


Unless I'm missing some trickery in the original comment, [] and {} are truthy values in JavaScript.

After some tests, I can confirm that they are true and false at the same time.

Javascript is weird.

I can't think of any case where those would be falsy. What exactly did you experiment with that made it appear that way?

Sanity check...

node -e "if (({})) console.log('truthy')" // requires wrapper to not interpret as block
node -e "if ([]) console.log('truthy')"

Logs truthy twice

[] == false // true
let obj = {}
obj == false // true

Oddly, node -e "if ([] == false) console.log('truthy')" logs truthy, but node -e "if ({} == false) console.log('truthy')" doesn't.

Oh Javascript...

The moral of the story: always use ===.

I used an extra variable for obj because {} == false got me a syntax error.

You have to wrap it in parens b/c JS treats toplevel curlies as a "block" rather than an object. But, of course, if you begin a line with parens, then it will become a function call on the previous line, if one exists, so for sanity's sake, begin any paren line with a semicolon (same for brackets).

Personally, I think it's really iffy to say that {} and [] are falsy values. I've always understood "falsy" to mean you can drop it into a conditional and it will behave like false would have:

$ node -p ';[false, null, undefined, 0, NaN, "", [], {}].map(v => [v?"X":"√︎",v])'
[ [ '√︎', false ],
  [ '√︎', null ],
  [ '√︎', undefined ],
  [ '√︎', 0 ],
  [ '√︎', NaN ],
  [ '√︎', '' ],
  [ 'X', [] ],
  [ 'X', {} ] ]

Here they all are. I realize that two of them will bring out the angry mob with their torches and pitchforks. But my disclaimer is that I did not write the language.

First the easy 6 falsy things:

  • false
  • 0
  • ""
  • undefined
  • null
  • NaN

Plus the final two falsy things, the second of which being an HTML-ism (part of the HTML specification):

  • -0
  • document.all
code of conduct - report abuse