2

I just ran across this code

var someBool = !!(o.a && o.a.t);

I was about to remove the double-negation, then realized it forces someBool to be a boolean value... Looking on the MDN, I find this example

a5 = "Cat" && "Dog"; // t && t returns "Dog"

This seems atypical based on my experience in other languages. I'd expect the logical and operation to always return a boolean value. Can anyone explain why this use case is supported in Javascript?

Also, is the code that sent me in this direction the best way to force a bool around logical and? I'm aware of new Boolean, but that doesn't return a primitive type like the double-negation, so perhaps that's the way to go?

quickshiftin
  • 66,362
  • 10
  • 68
  • 89

1 Answers1

4

The && and || operators have an effect similar to boolean AND and OR, but they don't affect the expression value. The expressions are evaluated and the values tested with the JavaScript "truthiness" rules, but the overall expression value is that of the actual operand expressions (well, one of them).

Yes, that's different from C and Java and etc. JavaScript is a different language with its own rules.

The Boolean constructor can be called without new to perform a "truthiness" test and return a boolean primitive. Using !! is fairly idiomatic however.

Pointy
  • 405,095
  • 59
  • 585
  • 614