5

I am practising the logical operators in JavaScript and fully understood the concepts, but It seems that I didn't with this equation.

    const one = 1;
    const two = 5;
    console.log(one && two);

Why in this case it returns five and not one, shouldn't be returned the first value since both are true ?

BeerusDev
  • 1,444
  • 2
  • 11
  • 30
Joey
  • 121
  • 2
  • 12
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND – BeerusDev Aug 26 '21 at 17:26
  • Refer these examples : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND#using_and – joy08 Aug 26 '21 at 17:27
  • 1
    Does this answer your question? [Logical operators in JavaScript — how do you use them?](/questions/4535647/logical-operators-in-javascript-how-do-you-use-them). `&&` evaluates to the first falsy operand or the last truthy operand. – Sebastian Simon Aug 27 '21 at 03:37

2 Answers2

5

From MDN on the && operator:

"If expr1 can be converted to true, returns expr2; else, returns expr1."

So in this case, 1 can be converted to true, so it returns the second value, 5.

bopbopbop
  • 487
  • 3
  • 9
2

The LOGICAL && operator returns the last value if all other values are true, or else it will return the first non truthy value.

i.e. Java != JavaScript

BeerusDev
  • 1,444
  • 2
  • 11
  • 30