Search code examples
javascriptlogical-operators

returning the higher value in logical operators in javascript


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 ?


Solution

  • 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 (numbers greater than 0 are truthy), so it returns the second value, 5.

    You see this pattern in JSX in React to conditionally render something:

    {something && <p>render me!</p>}