Flanagan\'s O\'Reilly JavaScript book states:
Unlike the && and || operators, the ! operator converts its operand to a boolean value [...] b
Per specification, section 11.11: Binary Logical Operators:
The production [of evaluating &&
] ... is evaluated as follows:
ToBoolean(lval)
is false, return lval. The production [of evaluating ||
] ... is evaluated as follows:
ToBoolean(lval)
is true, return lval. So internally the value is "converted to a boolean". However, since this is never exposed -- and the entire semantic explanation is an abstraction which can be/is "optimized out" -- the behavior of &&
and ||
can be simply explained through using truthy-and-falsy values (for which ToBoolean
covers: a truthy-value is one for which ToBoolean
returns true, all other values are falsy).
The logical table for &&
is:
a b result truthy any b falsy any a
The logic table for ||
is:
a b result truthy any a falsy any b
Note that either the evaluation of a
or b
is returned.
Happy coding.
For completeness, from section 9.2:
The abstract operation ToBoolean
converts its argument to a value of type boolean as ...
Because JavaScript has an idea of truthiness that covers more than booleans.
They do convert the values to boolean, but only to determine how to proceed in evaluating the expression. The result of the expression is not necessarily boolean (in fact, if neither of your operands are boolean, it will not give you a boolean):
var x = false || 'Hello' // gives you 'Hello'
var y = 0 && 1 // gives you 0, because 0 is "falsy" and short circuits
var z = 1 || 2 // gives you 1, because 1 is "truthy" and short circuits
The operands are interpreted as booleans for evaluating the expression, but the return value of && or || is always one of the operands.
For example:
true && 0 === 0, not false
1 || false === 1, not true