Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do the && and || operators convert their operands to booleans?

Tags:

javascript

Flanagan's O'Reilly JavaScript book states:

Unlike the && and || operators, the ! operator converts its operand to a boolean value [...] before inverting the converted value.

If those logical operators don't convert the operands to booleans, how can the expression be evaluated?

like image 230
ppecher Avatar asked Sep 29 '11 18:09

ppecher


1 Answers

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
like image 171
Pointy Avatar answered Oct 24 '22 21:10

Pointy