JavaScript Logical Operators (|| and &&) Explained with Examples – Asked in an HCL Tech Interview

JavaScript Logical Operators (|| and &&) Explained with Examples – Asked in an HCL Tech Interview

Our Code Expressions:

console.log(0 || 1); // ?
console.log(1 || 2); // ? console.log(0 && 1); // ? console.log(1 && 2); // ?

First, Understand the Logical Operators:

1. || (Logical OR)

  • Returns the first truthy value it finds.
  • If none are truthy, it returns the last value.
  • It short-circuits, stops evaluating once it finds a truthy value.

2. && (Logical AND)

  • Returns the first falsy value it finds.
  • If none are falsy, it returns the last value.
  • It also short-circuits, stops evaluating once it finds a falsy value.


Expression-by-Expression Breakdown

console.log(0 || 1);

  • 0 is falsy
  • 1 is truthy
  • || finds that 0 is falsy, so it keeps going and returns 1.

Output:

1


console.log(1 || 2);

  • 1 is truthy, so || returns it immediately without checking 2.

Output:

1

console.log(0 && 1);

  • 0 is falsy, so && stops and returns it right away.
  • Doesn’t even look at 1.

Output:

0

console.log(1 && 2);

  • 1 is truthy, so && evaluates the second operand.
  • 2 is also truthy, so it returns the last value.

Output:

2

✔ Final Answer:

A) 1 1 0 2

This question appeared in the HCL Tech interview, testing the candidate’s knowledge of boolean AND (&&) and OR (||) operator in JavaScript.





Post a Comment

Previous Post Next Post