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

Why && 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

+6
source share
5 answers

Think of && in JavaScript like this (based on ToBool from es5 spec )

 function ToBool(x) { if (x !== undefined) if (x !== null) if (x !== false) if (x !== 0) if (x === x) // not is NaN if (x !== '') return true; return false; } // pseudo-JavaScript function &&(lhs, rhs) { // lhs && rhs if (ToBool(lhs)) return rhs; return lhs; } 

Now you can see that ToBool("Cat") is true , therefore && will give rhs which is equal to "Dog" , then === does "Dog" === "Dog" , which means that the line gives true .


For completeness, the operator || it could be considered

 // pseudo-JavaScript function ||(lhs, rhs) { // lhs || rhs if (ToBool(lhs)) return lhs; return rhs; } 
+2
source

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 correct; otherwise returns false.

For the expression "Cat" && "Dog" first expression "Cat" cannot be converted to false or a boolean value, so it returns "Dog"

+11
source

Why does the && operator return the last value?

Because this is what he does. In other languages, the && operator returns a boolean value of true or false . In Javascript, it returns the first or second operand, which is also good, since these values โ€‹โ€‹themselves are already โ€œtrueโ€ or โ€œfalseโ€.

Therefore, 'Cat' && 'Dog' results in a value of 'Dog' , which is equal to 'Dog' .

+2
source

Because you asked if there is true === (true && true) . If you use a non-zero value in a boolean operation, javascript is converted to Boolean. Non-empty lines are "true", so they are true.

0
source

I assume that language developers wanted users to be able to use || operator as a "coalescing" operator in a style, for example. null coalesce operator? in c #.

In other words, if you want to use the default value, you can use the following idiom:

 var x = input || "default"; //x will be equal to input, unless input is falsey, //then x will be equal to "default" 
0
source

All Articles