+ 4

Javascript Question

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

9th Oct 2024, 10:16 AM
NEHA KURESHI
NEHA KURESHI - avatar
4 Respostas
+ 8
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
+ 7
Logical expressions are evaluated from left to right. && is a short-circuiting operator, meaning it will not evaluate any further if it encounters a false or falsey value. It's an optimization method, since false && anything after that will always be false, so no need to waste time going any further. If the first term is false or falsey, it will just return false or that falsey value then stop and not process the next value. But if the first value is true or truthy, && will evaluate and return the second value 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
+ 2
Thanks both of you😊
10th Oct 2024, 2:32 AM
NEHA KURESHI
NEHA KURESHI - avatar
0
Yh thanks
10th Oct 2024, 2:54 PM
Freda Biney
Freda Biney - avatar