How && and || Operators Work in JavaScript – Asked in Mindtree's 2nd Round JavaScript Interview. Javascript interview prepration.

How AND and OR Operators Work in JavaScript Asked in Mindtree 2nd Round JavaScript Interview

Understanding Logical Operators (|| and &&) in JavaScript

The given code uses logical OR (||) and logical AND (&&) operators with different values. Let’s break them down carefully.


🔹 First Expression:

console.log(false || null || "Hello");

Step 1: Understanding the || (Logical OR) Operator

  • The logical OR (||) operator returns the first truthy value it encounters.
  • If all values are falsy, it returns the last falsy value.

    Step 2: Evaluating the Expression (false || null || "Hello")

    We evaluate from left to right:

    1. false is falsy → move to the next operand.
    2. null is also falsy → move to the next operand.
    3. "Hello" is truthy → STOP and return "Hello".

      ➡ Output of First Expression:

      Hello

      🔹 Second Expression:

      console.log(false && null && "Hello");

      Step 1: Understanding the && (Logical AND) Operator

      • The logical AND (&&) operator returns the first falsy value it encounters.
      • If all values are truthy, it returns the last truthy value.

        Step 2: Evaluating the Expression (false && null && "Hello")

        We evaluate from left to right:

        1. false is falsy → STOP and return false (no need to check the rest).
        2. null and "Hello" are ignored because && stops at the first falsy value.

           Output of Second Expression:

          false

          Remember key points:

          1. The logical && (AND) returns the first falsy value (or the last truthy value if all are truthy).
          2. The logical || (OF)returns the first truthy value (or the last falsy value if all are falsy).

          ✔ Final Answer:

          A) Hello false

          This question appeared in the Mindtree 2nd round of interview, testing the candidate’s knowledge of Logical Operators like (&& and ||) operator in JavaScript.



          Post a Comment

          Previous Post Next Post