1

I got asked this question recently in an interview. I know that in JavaScript evaluation goes left to right. 1&&2 should be false right? I read in another ask here that 1&&2 returns 2. And that AND returns the first falsy value. But it felt vague. Can someone elaborate?

Nandhini A
  • 43
  • 3

6 Answers6

8
1 && 2 && 3 

same of

if (1) {
    if (2) {
        if (3) {
          return 3
        } else {
          return 3
        }
    } else {
        return 2
    }
} else {
    return 1
}


1 && 2 && 3  //3
1 && 0 && 3  //0
1 && false && 3  //false
false && 0 && 3  //false
1 && 0 && false  //0
str
  • 33,096
  • 11
  • 88
  • 115
Ghoul Ahmed
  • 4,478
  • 9
  • 23
7

The AND (&&) operator does the following:

  • Evaluates operands from left to right.

  • For each operand, converts it to a boolean. If the result is false, stops and returns the original value of that operand.

  • If all operands have been evaluated (i.e. all were truthy), returns the last operand.

In other words, AND returns the first falsy value or the last value if none were found. When all values are truthy, the last value is returned.

Ref: https://javascript.info/logical-operators

1&&2 should be false right?

Nope, in Javascript in a Boolean context, these values are converted to truthy. There are only six values that are converted to falsy and they are: false, 0, the empty string (e.g. '', ""), null, undefined, and NaN.

j08691
  • 190,436
  • 28
  • 232
  • 252
1

If the left hand side of && evaluates as a false value, the whole expression evaluates as the left hand side.

Otherwise it evaluates as the right hand side.

Thats why 1&&2&&3 gives you 3.

Super Man
  • 1,627
  • 1
  • 14
  • 25
1

logical AND && returns the last truthy value if all values are truthy or the first found falsy value.

console.log(1 && 2 && 3); // 3
console.log(1 && 0 && null); // 0
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
0

&& is the boolean AND operator over expressions. The evaluation of the partial expressions proceeds as usual, ie. the results are not 'true' boolean values but are interpreted to be 'truthy' or 'falsy' (implied by 12.13 of the ECMAScript standard).
Thus the JS engine MUST evaluate all expressions up to the first falsy value found (the overall result is then this first falsy value, interpreted as false) or until no further expression remains.
The standard mandates a left-to-right evaluation (12.13.3 of ECMAScript standard).

The precise Falsy/Truthy definitions are:

  • Falsy:
    One of false, 0, "", null, undefined, NaN
  • Truthy:
    Always unless being Falsy.

This is specified in the definition of the ToBoolean function in section 7.1.2 of the standard. Also see the glossary at MDN for a crisp summary (falsy, truthy)

collapsar
  • 15,446
  • 3
  • 28
  • 56
0

All the numbers other than 0 returns true on & performing && and when all operands are true && returns the righteous value 1&&2 returns 2 and 2&&3 will return 3