1

I had checked for many test cases. It's looking if the first value is true and it's returning the second value.

Example:

2 && 5 // --> 5
5 && 10 // --> 10
0 && 2 // --> 0

Why doesn't it return either True or 1?

LostMyGlasses
  • 3,074
  • 20
  • 28

2 Answers2

1

Per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Description,

Operator: Logical AND (&&)

Usage: expr1 && expr2

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.

Community
  • 1
  • 1
Cody G
  • 8,368
  • 2
  • 35
  • 50
  • beat me to it! here's another way to say it as well in the interest of helping people understand `Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value` – zfrisch Aug 30 '18 at 17:22
  • Aren't we supposed to close the duplicates instead of answering them? – raina77ow Aug 30 '18 at 17:29
  • Sure. https://meta.stackoverflow.com/questions/315936/what-to-do-when-a-high-rep-user-answers-a-low-quality-off-topic-or-duplicate-qu – Cody G Aug 30 '18 at 17:48
  • @raina77ow you literally can't answer once it's marked duplicate, but if you don't notice that it's a duplicate and answer before that happens, that's not really anyone's fault. – zfrisch Aug 30 '18 at 19:22
0

The && operator will return the last value if all other values are truthy, otherwise it will return the first non truthy value. So, as in 0 && 2, 0 is non-truthy, that gets returned.

  • 1
    Just for fun, two other ways to phrase: 1) `&&` returns the left hand side if it is falsy, otherwise it returns the right hand side. 2) Boolean operators return the first operand that determines the overall result (<- this is maybe harder to grasp, but correct). – Felix Kling Aug 30 '18 at 17:38