Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logical operator && and two strings in javascript

When I use the logical operator && between two strings, why does it give me the second string as output:

console.log("" && "Dog");    // ""  console.log("Cat" && "Dog"); // "Dog"

I realize that the with the exception of 0, false, null, undefined, "" and NaN, everything else is evaluated as a boolean true in a logical expression like the one above. But why is the output the second string and not the first? And why is the ouput not just "true" since it is being evaluated as a boolean expression?

like image 333
Ashesh Avatar asked Jun 19 '13 20:06

Ashesh


People also ask

What are logical operators example?

In MATLAB®, there are three logical operators: & (logical AND), | (logical OR), and ~ (logical NOT). Like the relational operators, they can be used as arithmetical operators and with scalars, matrices and arrays.

What are the 3 logical operators?

There are three logical operators: and , or , and not . The semantics (meaning) of these operators is similar to their meaning in English.

What are the 5 logical operators?

There are five logical operator symbols: tilde, dot, wedge, horseshoe, and triple bar.


1 Answers

in the expression

"Cat" && "Dog" // => "Dog" 

Because you're using &&, JavaScript is promising you that it will verify that both sides of the expression are true. In this case, "Dog" is the just the last evaluated thing.

To be more explicit, you could do something like

var c = "Cat" != null && "Dog" != null 

It's a little bit more wordy, but this boils down to

var c = true && true console.log(c) // => true 

If you want a simple shortcut for the boolean, use the Boolean constructor -

var c = Boolean("Cat" && "Dog") console.log(c) // => true 

If you just use a simple REPL or JavaScript console, you'd be able to see this output very easily.


Per one of the comments below

Using ||, JavaScript is promising you that at least one of the sides is true. Since "Cat" is true, it stops there and returns "Cat". This is known as Short-circuit evaluation

like image 181
Mulan Avatar answered Oct 05 '22 10:10

Mulan