Can (a == 1 && a == 2 && a == 3)
be evaluated as true
?
This is an interview question from a large technology company. I'm trying to find the answer. I know we never wrote this code in our day-to-day life, but I'm curious.
Can (a == 1 && a == 2 && a == 3)
be evaluated as true
?
This is an interview question from a large technology company. I'm trying to find the answer. I know we never wrote this code in our day-to-day life, but I'm curious.
It is possible if a
is a constant object that returns values that are incremented each time the object is invoked. In the case below:
const a={
valor: 1,
valueOf: function(){
return a.valor++;
}
}
On the first invocation of a
it will return 1
. After this, every time% w_ of% is called, it will return the last value a
(1, 2, 3 ...).
Therefore,% w_ of% will be true, because w_% will be equal to 1, 2, and 3 returned from the% w_% constant.
When I invoke +1
, the value of (a == 1 && a == 2 && a == 3)
is a
(true) and a
becomes value a == 1
, so a
is also true, and so on
For example, you could do that too the result is the same:
const a={
valor: 1,
valueOf: function(){
return a.valor++;
}
}
if(a == 1 && a == 2 && a == 3 && a == 4 && a == 5){
// até esse "a" no console.log abaixo já incrementa o valor
console.log("fim. O valor de a é "+a);
}
There is a similar question in SOen .