Not Just True or False: How JavaScript Handles && and || with Numbers and logic behind Short-Circuiting. Mastering JavaScript Logic: What Really Happens with 5 && 1 and 5 || 1?

Not Just True or False How JavaScript Handles AND and OR with Numbers and logic behind Short-Circuiting Mastering JavaScript Logic What Really Happens with 5 AND 1 and 5 OR 1

Let’s break down exactly what’s happening under the hood in each of these lines:

console.log(5 && 1);
console.log(5 || 1);

Understand Truthy vs. Falsy in JavaScript

  • Falsy values are those that, when converted to Boolean, become false. There are exactly six of them:
        false, 0, "" (empty string), null, undefined, and NaN.

  • Truthy values are everything else—including nonzero numbers like 5 and 1.

Whenever you use && or ||, JavaScript doesn’t just return true or false—it actually returns one of the operands themselves. Which one depends on truthiness and the operator’s short‑circuit logic.


1. The && (Logical AND) Operator

Semantics
A && B evaluates A first:

  1. If A is falsy, immediately return A (and skip evaluating B).
  2. Otherwise (A is truthy), evaluate and return B.

In plain English: “Both must be truthy; if the first one already fails, give me that failure; otherwise, give me the second one.

Applying it to 5 && 1

  1. Evaluate the left operand, 5.
    • 5 is truthy.
  2. Since the first operand passed the truthy check, evaluate the right operand, 1.
    • 1 is also truthy.
  3. Return the value of the right operand, 1.

console.log(5 && 1); // → 1

2. The || (Logical OR) Operator

Semantics
A || B also evaluates A first:

  1. If A is truthy, immediately return A (and skip evaluating B).
  2. Otherwise (A is falsy), evaluate and return B.

In plain English: “Give me the first one that succeeds; if the first is good, I don’t even care about the second.

Applying it to 5 || 1

  1. Evaluate the left operand, 5.
    • 5 is truthy.
  2. Because the first operand is truthy, we short‑circuit: we don’t even look at 1.
  3. Return the value of the first operand, 5.

console.log(5 || 1); // → 5

Why Does JavaScript Return the Operand Instead of true/false?

This design lets you do clever default‑value patterns:

let name = userInput || "Anonymous";
// If userInput is falsy (e.g. ""), name becomes "Anonymous". // Otherwise name becomes the actual userInput.

And && can guard execution:

isLoggedIn && showSecretPage();
// Only calls showSecretPage() if isLoggedIn is truthy.

✔ Final Answer:

C) 1 5

This question appeared in the Infosys 1st round of interview, testing the candidate’s knowledge of && and || operator and its short circuit behavior in JavaScript.

Post a Comment

Previous Post Next Post