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 ?
JavaScript uses the double ampersand ( && ) to represent the logical AND operator. The following expression uses the && operator: let result = a && b; Code language: JavaScript (javascript) If a can be converted to true , the && operator returns the b ; otherwise, it returns the a .
Logical Operators && is the logical and operator. It returns TRUE if both of the arguments evaluate to TRUE.
Remarks. The logical OR operator ( || ) returns the boolean value true if either or both operands is true and returns false otherwise. The operands are implicitly converted to type bool before evaluation, and the result is of type bool .
Logical AND ( && ) evaluates operands from left to right, returning immediately with the value of the first falsy operand it encounters; if all values are truthy, the value of the last operand is returned.
Logical operators There are four logical operators in JavaScript: || (OR), && (AND), !
And the logical AND && operator is work with two or more operands. If a can be converted to true, the && operator returns the b; otherwise, it returns the a. In fact, this rule is applied to boolean values.
But, like the logical or operator, the logical and operator doesn't necessarily return a boolean: Given a chain of multiple logical and operators a && b && c && d, JavaScript returns the left-most falsy value. View more jobs!
Their result can also be of any type. Let’s see the details. The “OR” operator is represented with two vertical line symbols: In classical programming, the logical OR is meant to manipulate boolean values only. If any of its arguments are true, it returns true, otherwise it returns false.
From MDN on the && operator:
"If
expr1
can be converted totrue
, returnsexpr2;
else, returnsexpr1
."
So in this case, 1
can be converted to true
, so it returns the second value, 5
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With