This is an interview question:
Is it possible Javascript
that you (a == 1 && a == 2 && a == 3)
can evaluate true
?
Reference: Related question on SOen
This is an interview question:
Is it possible Javascript
that you (a == 1 && a == 2 && a == 3)
can evaluate true
?
Reference: Related question on SOen
If we analyze how the operator works
==
we see that, for example, if the variableA
is aObject
and it is compared against the variableB
of typeNumber
, that is:Solution:
We can define a
a
as an object with a methodtoString
(orvalueOf
) which changes its result each time it is called.Example
Reference: Original answer on SOen
You could use
defineProperty
to define the methodget
of the objecta
, which will do is define or raise an internal property and return its value: