Saturday 20 January 2018

javascript - Can (a== 1 && a ==2 && a==3) ever evaluate to true?






Moderator
note:
Please resist the urge to edit the code or remove this notice. The
pattern of whitespace may be part of the question and therefore should not be tampered
with unnecessarily. If you are in the "whitespace is insignificant" camp, you should be
able to accept the code as
is.





Is
it ever possible that (a== 1 && a ==2 && a==3)
could evaluate to true in
JavaScript?



This is an interview question asked
by a major tech company. It happened two weeks back, but I'm still trying to find the
answer. I know we never write such code in our day-to-day job, but I'm
curious.



Answer




If you take advantage of href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#Loose_equality_using"
rel="noreferrer">how == works, you could simply
create an object with a custom toString (or
valueOf) function that changes what it returns each time it is
used such that it satisfies all three conditions.



class="snippet" data-lang="js" data-hide="false" data-console="true"
data-babel="false">

class="snippet-code-js lang-js prettyprint-override">const a =
{
i: 1,

toString: function () {
return
a.i++;
}
}

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






/>

The reason this works is due to the use of the loose
equality operator. When using loose equality, if one of the operands is of a different
type than the other, the engine will attempt to convert one to the other. In the case of
an object on the left and a number on the right, it will attempt to convert the object
to a number by first calling valueOf if it is callable, and
failing that, it will call toString. I used
toString in this case simply because it's what came to mind,
valueOf would make more sense. If I instead returned a string
from toString, the engine would have then attempted to convert
the string to a number giving us the same end result, though with a slightly longer
path.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...