Ashesh
Ashesh

Reputation: 949

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?

Upvotes: 41

Views: 30653

Answers (6)

msa_iqbal
msa_iqbal

Reputation: 11

The && (logical AND) operator in JavaScript works by evaluating expressions from left to right and returning the first falsy value it encounters. If there are no falsy values, it returns the last evaluated value.

Let's break down each case:

Case 1

console.log("" && "Dog"); // Output: ""
  1. "" is a falsy value in JavaScript.
  2. When the && operator encounters a falsy value ("" in this case), it stops and returns that value immediately without evaluating the rest.
  3. So, the output is "".

Case 2

console.log("Cat" && "Dog"); // Output: "Dog"
  1. "Cat" is a truthy value.
  2. Since the first value is truthy, && moves to evaluate the next expression, which is "Dog".
  3. "Dog" is also truthy, so && reaches the end of the expression and returns the last truthy value it evaluated, which is "Dog".

In summary:

  • && stops at the first falsy value or returns the last truthy value if none are falsy.

Upvotes: 1

Emre Akgül
Emre Akgül

Reputation: 1

You can do it much simpler:

To verify that a string is empty, you can use the ! operator also in javascript.

let a = '';
console.log(!a);  // => true

a = 'foo';
console.log(!a)   // => false

If you use this operator again, now you are negating a boolean instead of a string. In your case:

console.log(!!'' && !!'Dog');    // => false
console.log(!!'Cat' && !!'Dog'); // => true

you can also look at this article: Double negation (!!) in JavaScript - what is the purpose?

Upvotes: 0

FrancescoMM
FrancescoMM

Reputation: 2960

Because of the way logic works, if you need to test if both items are true, and you already know the first item is true, then the test totally depends on the second item.

true && someValue is equivalent to just someValue

For this reason, the operator && can be handled by returning its operands instead of true/false values, and just testing the first operand and not the second

a && b:

  • if a evaluates to false, no need to test further, return a (as it's false)

  • else if a evaluates to true, the result totally depends on b, so just return b (no need to test if b evaluates to true or false, just return it)

In code this is like

function and(a,b) {
    if(!a) return a;
    return b;
}

Similarly operator || can be defined as

function or(a,b) {
    if(a) return a;
    return b;
}

Returning operands instead of true/false has a few advantages:

  • requires less evaluations (notice b is never evaluated, in both cases)

  • does not require a definition of true/false so it works more broadly, even cross language or if the value of "true" changes

  • can be "hacked" to be used, without an if, to do stuff like string1 && string2 that has a useful meaning: "if string1 is not empty use string2 otherwise keep it empty (to replace every word of a string with the text "word": aString.split(" ").map(function(word) {return word && "word"});

JavaScripters love that kind of stuff (exploiting one operator side effect out of the usual context to get a different, unexpected behaviour), they do this to show off language knowlodge at parties. :D

Upvotes: 0

Mulan
Mulan

Reputation: 135197

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

Upvotes: 42

Answer by @naomik pretty much covers it. If you want to go deep, I suggest taking a look at the ECMAScript specification, section 11.11:

http://www.ecma-international.org/ecma-262/5.1/#sec-11.11

In the "Semantics" section, we can see:

The production LogicalANDExpression : LogicalANDExpression && BitwiseORExpression is evaluated as follows:

  1. Let lref be the result of evaluating LogicalANDExpression.
  2. Let lval be GetValue(lref).
  3. If ToBoolean(lval) is false, return lval.
  4. Let rref be the result of evaluating BitwiseORExpression.
  5. Return GetValue(rref).

Upvotes: 14

Matti Mehtonen
Matti Mehtonen

Reputation: 1705

I think this is because of nature of logical operator &&. Javascript executes expression "cat" && "Dog" in following way:

Checks the value "cat" - it returns something else than "", 0, null, undefined or false and is truthy. Javascript sees && and so it continues expression and faces string "Dog", which is something else than "", 0, null, undefined or false and is truthy, expression ends and expression returns the last value it checked.

If you replace && with || expressions ends at first truthy value and thats way

var boolean = "cat" || "dog"

returns first value: cat

Upvotes: 17

Related Questions