Interviewer: Can (a==1 && a==2 && a==3) Ever Evaluate to ‘true’ in JavaScript?

Yes, it can be true, and there are 6 ways — amazing!

fatfish
4 min readSep 18

--

Photo by Mikhail Vasilyev on Unsplash

Recently, I was asked a very interesting interview question: Can (a== 1 && a==2 && a==3) ever evaluate to true in JavaScript?. I almost lost the job opportunity because I couldn’t answer.

At that moment, I was shocked by the question and thought the interviewer was joking.

But when I saw his “smile”, a feeling of “you must not know the answer” crossed through my mind. It was definitely not an easy problem to solve.

The article will give 6 professional answers. Let’s start right away.

Solution 1: valueOf && toString

The first solution is very simple, and I’m sure you’ll have an idea once you’ve read this code.

It’s amazing, what’s going on? Don’t worry, my friend, I will try to explain why.

Explaining part of the implicit conversion rules

When == is used to compare two values in JavaScript, the following operations are performed:

  1. Convert the two compared values to the same type.
  2. After conversion (one or both sides of the equation may be converted), compare the values.

The comparison rules are shown in the following table:

--

--

fatfish

Hi friends, I am a front-end engineer from Alibaba, let’s code happily together.