Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the following true: "Dog" === ("Cat" && "Dog")

Tags:

javascript

Why does the && operator return the last value (if the statement is true)?

("Dog" == ("Cat" || "Dog")) // false
("Dog" == (false || "Dog")) // true
("Dog" == ("Cat" && "Dog")) // true
("Cat" && true) // true
(false && "Dog") // false
("Cat" && "Dog") // Dog
("Cat" && "Dog" && true) // true
(false && "Dog" && true) // false
("Cat" && "Dog" || false); // Dog

Fiddle

like image 364
Jonathan Avatar asked Feb 17 '14 13:02

Jonathan


Video Answer


1 Answers

Logical Operators - && (MDN)

Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.

For your expression "Cat" && "Dog" , the first expression "Cat" can't be converted to false or a boolean value, hence it returns "Dog"

like image 198
Habib Avatar answered Oct 11 '22 13:10

Habib