+ 3

Javascript Question

Why And operator returns 2?? console.log(1 && 2)

9th Oct 2024, 10:16 AM
NEHA KURESHI
NEHA KURESHI - avatar
2 odpowiedzi
+ 4
In JavaScript, the && (AND) operator evaluates expressions from left to right and returns the first falsy value it encounters. If all values are truthy, it returns the last evaluated value. In the expression 1 && 2, both 1 and 2 are considered truthy values. Since there is no falsy value, the operator returns the last evaluated value, which is 2. So, console.log(1 && 2) prints 2 because both 1 and 2 are truthy, and 2 is the final value in the expression.
9th Oct 2024, 11:51 AM
Melkon
Melkon - avatar
+ 2
Logical expressions are evaluated from left to right. 1 is truthy, so && evaluates the value after it, which is 2. so 2 is passed to console.log https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND
9th Oct 2024, 11:19 AM
Bob_Li
Bob_Li - avatar