Predict the output: does && return a boolean?
Answer out loud or in your head first, then compare.
Answer
Not always. The && operator returns the first falsy operand, or the last operand when all the earlier ones are truthy. It uses short-circuit evaluation.
JavaScript
let a = 0;
let b = 0;
function run() {
b++;
console.log(a && b);
}
run(); // 0
console.log('ok' && 42); // 42
console.log(Boolean('ok' && 42)); // truePitfall in React: count && <Badge /> can render 0. If the condition should be a boolean, I write count > 0 && <Badge />.
The code adapts a predict-the-output question, with an explicit function call.
How did it go? Be honest — “Not yet” puts the question on your review list.
Related questions
- What does 'ok' && 42 return? — JavaScript
- What does count && <Badge /> render when count = 0? — React