(a== 1 && a ==2 && a==3): Can ever evaluate to true in Javascript?

Can you believe there’s this interesting interview question from a big tech company? They asked if it’s possible for (a == 1 && a == 2 && a == 3) to be true in JavaScript! It came up in my interview two weeks ago, and I’ve been pondering it since. I know it’s not something we typically code in our daily work, but let’s figure out the answer.

Here is the explanation

Hey there! Check out this cool trick I stumbled upon! So, if you play around with how the == operator works, you can create an object with a custom toString (or valueOf) function. This function changes what it returns each time it’s used, making it satisfy all three conditions.

Take a look:

const a = {
  i: 1,
  toString: function () {
    return a.i++;
  }
}

if (a == 1 && a == 2 && a == 3) {
  console.log('Hello World!');
}

It’s a bit quirky, but it works because of the loose equality operator. When you use loose equality, the JavaScript engine tries to convert operands of different types. In this case, with an object on the left and a number on the right, it attempts to convert the object to a number.

The engine first calls valueOf if it’s callable, and if not, it calls toString. I used toString here just because it came to mind, but valueOf would make more sense. Give it a shot, and you’ll see the magic unfold!

Another explanation for this

Absolutely! It’s a clever trick using JavaScript’s loose equality (==) operator. Here’s a simple breakdown:

In JavaScript, when you compare values using ==, the engine tries to convert them to the same type if they’re different. For this question, someone can create an object (let’s call it ‘a’) with a custom toString function. This function changes what it returns each time it’s called.

const a = {
  i: 1,
  toString: function () {
    return a.i++;
  }
}

if (a == 1 && a == 2 && a == 3) {
  console.log('Hello World!');
}

The object ‘a’ is compared with 1, 2, and 3 in sequence. The toString function, when called, returns ‘a.i’ and increments it each time. This allows ‘a’ to behave like 1, 2, and 3 in different comparisons.

In simpler terms, it’s a bit of a JavaScript puzzle where the object changes its value dynamically during the comparisons, making the condition true. It’s a fun trick but not something you’d use in everyday coding!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top