Intern
What is the feature of performing the logical 'AND' operation?
sobes.tech AI
Answer from AI
The feature of the logical 'AND' operation (&&) in JavaScript is its lazy (short-circuit) evaluation of operands:
- The left operand is evaluated.
- If the left operand is falsy (
false,0,"",null,undefined,NaN), then the right operand is not evaluated, and the entire expression's result becomes the value of the left operand. - If the left operand is truthy, then the right operand is evaluated, and the result of the entire expression becomes the value of the right operand.
This allows && to be used not only for condition checking but also as a compact alternative to if for executing actions or assigning values when the first condition is true (idiom "short-circuit evaluation").
// Example of lazy evaluation
let count = 0;
true && count++; // count becomes 1
false && count++; // count remains 1, the right operand was not executed
// Example of using as an alternative to if
let userData = { username: 'test' };
let username = userData && userData.username; // username will be 'test' if userData is not null/undefined
let config = null;
let options = config ?? { timeout: 1000 }; // Using ?? for a more explicit check for undefined/null
// Using &&: let options = config || { timeout: 1000 }; - works differently