Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `1 && true` get a bool value `true`, but `0 && true` get a number `0`?

Tags:

javascript

Why does 1 && true get a bool value true, but 0 && true get a number 0? I tested it in Chrome Console and Firebug.

like image 672
user805627 Avatar asked Nov 02 '12 20:11

user805627


3 Answers

Because expr1 && expr2 will return expr1 if it is false, otherwise it will return expr2.

like image 162
Justin Niessner Avatar answered Nov 14 '22 07:11

Justin Niessner


Because that is how logical operators in Javascript are defined to behave.

Additional reference: ECMA 262, page 83.

like image 31
lanzz Avatar answered Nov 14 '22 08:11

lanzz


The && operator is commonly called logical and. If the first operand is false, null, undefined, "" or the number 0 then it returns the first operand. Otherwise, it returns the second operand

like image 24
Rahul Tripathi Avatar answered Nov 14 '22 08:11

Rahul Tripathi