
Can (a ==1 && a== 2 && a==3) ever evaluate to true? - _nalply
https://stackoverflow.com/questions/48270127
======
russdill
This is also possible under c, assuming a is declared volatile, or if the
compile chooses not to optimize out the always false statement and tests a 3
times in sequence.

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

| Ummm...hmm... no...?

> Wrong. Nothing is impossible. Next question. You are unable to use
> JSON.parse(JSON.stringify(x)), how do you clone x?

| Hmm, I'm actually not sure... its certainly possible...

> Appreciate your honesty, the correct answer is: you don't. Thank you for
> your time, we'll be in touch.

------
natecavanaugh
It sounds like the interviewer did this person a favor. It's a clever trick,
and I've abused toString and toJSON for plenty, but if this is a "major tech
company", do you really think it's a great workplace if they think being able
to read incomprehensible code, and instead of fixing said code, they use it as
a filter?

I doubt they have that code in production, but even then, devs that are
enamored with hacks like this and knowing pedantic answers to trick questions,
chances are, their coding style will reflect just how "clever" they think they
are.

------
senorerik
As long as we're writing bad code, here's my stab at the code golf version:

    
    
      i=0,a={valueOf:_=>++i}
    

\- Omitting the variable statements in non-strict mode creates global
(function scoped) variables

\- The comma operator evaluates its operands left to right and returns the
rightmost operand, the result of which is irrelevant in this case

\- The arrow function allows us to omit parenthesis around the function
parameters, so any single character variable name works (in this case _)

\- The arrow function syntax also allows us to omit the curly braces, and will
automatically return the body of the function.

\- Automatic Semicolon Injection allows us to omit the trailing ;

------
kazinator

      This is the TXR Lisp interactive listener of TXR 188.
      Quit with :quit or Ctrl-D on empty line. Ctrl-X ? for cheatsheet.
      1> (defstruct incster nil
           (val 0)
           (:method equal (me) (inc me.val)))
      #<struct-type incster>
      2> (let ((a (new incster)))
           (and (equal a 1) (equal a 2) (equal a 3)))
      t
    

:)

Equality substitution: [http://www.nongnu.org/txr/txr-
manpage.html#N-00790C76](http://www.nongnu.org/txr/txr-
manpage.html#N-00790C76)

------
JoeAltmaier
In a C macro this is a classic problem - if 'a' is an argument to a macro, and
'i++' is provided to the macro, and 'i' had the value of 1, then this could
evaluate to true.

~~~
contravariant
Or you could just trigger undefined behaviour, in which case it _might_
evaluate to true.

------
bfsg
It's a debug related question because it tests whether you realise "a" can be
a getter. For the rest this line of code is so hideous, although it is
accepted by the interpreter, it is in every aspect totally wrong to do such
thing in your codebase.

This is a typical example of what is wrong and annoying with job interview
questions. In a way it doesn't really matter if the line could possibly
evaluate to true, it shouldn't be written in the first place. What in the
world tells your NO answer about your skill to do the job you are applying
for? That you're not smart enough? Come on, I'd be really pissed off with shit
like this.

~~~
FabHK
You might have bugs in the real world that are caused by language features or
idiosyncrasies that are visible in this artificial, small (thus more easily
understood) toy example.

I often find these toy examples or trick questions (also in the context of C++
inheritance, for example) very instructive.

------
rmrfrmrf
I was thinking something like

    
    
        Number.prototype.toString = () => '';
    
        let a = '';
    

Although I always forget which side gets coerced (this would assume the right-
hand side does). I like the side-effect approach, though — seems more nuanced
and probably what they were looking for.

------
_Microft
This is what I came up with:

    
    
      var i = 0;
      window.__defineGetter__("a", function() { i++; return i; });
      if(a === 1 && a === 2 && a === 3) {
        "Wtf";
      }

~~~
Sephr
Also works with valueOf:

    
    
        let i = 0, a = {valueOf: () => ++i};
        if (a == 1 && a == 2 && a == 3) {
            console.log("all equal");
        }
    

Object.defineProperty (modern version of __define[GS]etter__):

    
    
        let i = 0;
        Object.defineProperty(self, "a", {get: () => ++i});
        if (a == 1 && a == 2 && a == 3) {
            console.log("all equal");
        }

~~~
_Microft
Mix it with a pseudo-random number-generator for extra fun.

    
    
      var i = 0;
      window.__defineSetter__("x", function(value) { i = value; });
    
      window.__defineGetter__("x", function() {
        // LCG, a = 4, c = 1, m = 9;
        i = (4 * i + 1) % 9;
        return i;
      });  
    
      x = 3;
      if(x === 4 && x === 8 && x === 6) {
        "wtf!";  
      }

------
inopinatus
Some of the answers depend on tricks with Unicode strings and I have
encountered bugs where a bad cut-and-paste via chat program led to a character
substitution that was not apparent to the human eye but led to a subtle
misbehaviour.

------
d--b
The fact that you can bend javascript to make it do this is not particularly
remarkable.

The fact that there are 5 or 6 completely different ways to accomplish this is
boggling!

------
Spivak
Question about the first answer, is there anywhere in the spec that demands
this behavior? If the JS interpreter silently 'optimized' the branch into

    
    
        var a_ = a.toString();
        if (a_ === "1" && a_ === "2" && a_ === "3") {
            ...
    

or really just

    
    
        if(false) {
            ...
    

would it be in violation?

~~~
tlb
I believe so, if 'a' resolves to a getter. To optimize, it would have to prove
that 'a' is a locally bound variable with no escapes or else no functions are
called in the comparison.

See [https://v8project.blogspot.com/2017/09/disabling-escape-
anal...](https://v8project.blogspot.com/2017/09/disabling-escape-
analysis.html) for a related bug.

------
idbehold
Open your browser console and find an input that works:

    
    
       function test (a) {
         try {
           return !!(typeof a === 'undefined' && a(1) && a[2])
         } catch (e) {
           return false
         }
       }
    

It is possible to get it to return true.

~~~
Zirro
I've found a solution which I presume is the one you have in mind, though it's
worth noting that it doesn't work in Firefox at the moment.

Feel free to add a link with your answer later on, just in case you came up
with something different.

------
mrmattyboy
I really wanted to comment suggesting something like this, although I don't
know how to do it in any language...

Everyone suggested methods of changing the value of 'a', but what if the ==
operator is changed to something that returns true for these comparisons?

~~~
anamexis
This is possible in many languages, but not in JavaScript, because it does not
support operator overloading.

------
snake_plissken
Wooo that is dirty.

In general, I'm not sure how to feel: 75% not ok, and 25% ok with this type of
question? As much as I despise these types of interview questions and this
type of interviewing process, reading about them after the fact is always
enlightening.

~~~
TheRealPomax
It's a pretty ridiculous interview question, but a really nice example to
highlight part of the internals of the ECMAScript language specification. It's
great to ask in a teaching environment, but insane to ask as a test of
competency (unless the job required truly deep knowledge of the language
specification).

------
sendben2
Yes if a represents a function that is testing a call condition like isNumber
or is less than 4

------
pvtmert
i first thought about a is a volatile (in C/C++) and external clock is
incrementing A just right or easily you pass some PC (program counter) as
reference to fn(int &a); protoyped function

------
tathougies
This is an interview question? Any company willing to use a language with such
little reasoning ability is not one I would ever want to work at. Especially a
company that would use any bizarre features that would enable this.

------
singularity2001
spoiler: yes in js it can

now that you know the answer try to come up with a solution.

------
floriferous
Is there any way this could work with === ?

~~~
_nalply
Yes, one answer on SO showed a possibility. The first getter overwrites a with
a getter giving 2, then this second getter overwrites a with a getter giving
3. Crazy.

------
jjuhl
Anyone who does something like this in production code ... shouldn't be
writing production code...

~~~
TheRealPomax
The problem is that production code never looks like the toy problem you can
reduce it to. Someone could write the exact same thing but make it look
reasonable, or even "a sweet hack", using an object property getter instead of
a function to move something along in a finite state machine:

    
    
      if (state.step == DFA.INITIALIZED && state.step == DFA.RUNNING) {
        ...
      }

~~~
earenndil
In this case they should use bitfields and bitflags.

~~~
TheRealPomax
Of course you should. No "look at this cool hack" exists that doesn't have a
safer, easier to trace equivalent.

Doesn't mean you won't find those hacks in a million code bases used in
production, though, and a professional knowledge of "yeah.. okay that's
possible, but come on" isn't a bad thing to have.

------
abakker
can you just overload the operators '==' and '&&' to mean something else?

Like, set 'a' to contain a string like '0123456789' and then overload '==' to
just mean "check if this number is in the string" then it works.

~~~
jontro
You cannot overload operators in javascript

------
Upvoter33
yes in a concurrent program

~~~
jandrese
Is concurrent javascript a thing?

~~~
kodablah
It's environment specific, but in general w/ web workers it is a thing, but
they can't update the same var (used to be able to update a shared array until
just recently though :-)

------
DaniFong
yes, at very high speeds

------
danjoc
>This is interview question asked by a major tech company. >They said nothing
is impossible. >Dimpu Aravind Buddha

"Anything is possible? Then show me your perpetual motion devices perhaps? Do
you compare equality to three different values often in production? Do you ask
this question to all candidates, or just the Indians? Are these like the
'Jewish Problems' they used to ask at Moscow State University entrance exams?"

When I read interview experiences like these, it explains a lot about Silicon
Valley's diversity problems to me.

------
jandrese
Context is important here. If you make it clear that underhanded tricks are on
the table then yes. Is is reasonable as an honest programming mistake? No.

This feels like handing some prospective code monkey an example from the
Underhanded C contest without warning them first. Very few people are going to
pass that test.

~~~
weberc2
It doesn't have to even be "underhanded". Libraries like SQLAlchemy overload
`==` to return a piece of a query predicate (e.g., `foo == 0` => `WHERE foo =
0`), similarly, if I recall correctly, there's an overloaded `and` operator,
which performs a similar function. Because Python is truthy and these
operators return objects, I think this may evaluate to `True` without being
deliberately underhanded. Granted, building a query predicate `WHERE a = 1 AND
a = 2 AND a = 3` isn't a useful thing to do in the first place, but still not
underhanded.

~~~
greenshackle3
Nitpick, SQLAlchemy overrides the binary operators (~, &, |) for query
construction, not the logical operators (and, or, not). It also has its own
operators you can import (and_, or_, etc.)

And you are right, it can easily lead to mistakes; if you use logical
operators by mistake when building a query, you will probably get 'True'
instead of a query object.

~~~
weberc2
I appreciate your nitpick! It's been a little while since I used SQLAlchemy,
and I did run into surprises with these overloaded operators.

------
zerostar07
you could also overload the && operator for extra confusion

~~~
cpburns2009
I know you can in C++, but in JavaScript? Are you sure about that?

~~~
zerostar07
oops i missed that bit

------
Koshkin
In C++ this is easy, assuming that 'a' is a value of a custom class.

~~~
kazinator
C++ being a dialect of C, you can simply make _a_ a preprocessor macro
expanding to _i++_.

The expression uses the && operator, which is properly sequenced so no
undefined behavior occurs in that case.

Though you might think that it's an incredibly bad idea, in fact the C
standard library allows the _getc_ and _getchar_ functions to be defined as
macros, and in fact they historically have been. Thus something like
_getc(stream) << 8 + getc(stream)_ stuffs multiple side effects into the same
expression without a sequence point (not to mention neglecting to check the
return values for EOF).

Each _getc_ call wants to inspect and increment some buffer pointer, like

    
    
       #define getc(s) ((s)->in < (s)->in_filled \
                        ? (s)->buf[(s)->in++] \
                        : __real_getc(s))
    

We're _not_ okay on account of the ?: sequencing, because the expression
(A?B:C)+(X?Y:Z) doesn't sequence A relative to Z; there no sequence point
between them. The two branches of the + can evaluate in parallel/interleaved
fashion.

~~~
mark-r
In C or C++ you can't rely on multiple ++ in a single statement doing anything
sensible.

~~~
foxhill
actually it is defined, i believe you mean sequence point - in which case
multiple updates are indeed undefined.

however, unless i'm mistaken,

    
    
        a && b && c
    

is 3 distinct sequence points, in which case, the behaviour is in fact well-
defined.

------
rcdmd
Reminds me of my all time favorite programming talk-- (4:17)
[https://www.destroyallsoftware.com/talks/wat](https://www.destroyallsoftware.com/talks/wat)

~~~
leipert
Which reminds me of the perl jam (29 min)
[https://media.ccc.de/v/31c3_-_6243_-_en_-
_saal_1_-_201412292...](https://media.ccc.de/v/31c3_-_6243_-_en_-
_saal_1_-_201412292200_-_the_perl_jam_exploiting_a_20_year-old_vulnerability_-
_netanel_rubin)

~~~
madsohm
It's a nice talk, but does he have to swear so much?

~~~
leipert
I don't know, I think it's just how you are... Some people swear, other's
don't. And I think it easier to be cynical/sarcastic than to criticize in a
positive way. This is especially true, if you are

a) limited in time, because you do research in your free time.

b) getting negative, or even worse, no or ignorant feedback by the other
party.

c) getting tired, because you preach the same stuff over and over again.

I think is really hard to do responsible disclosure and maintain a calm
attitude during the whole process. There is this awesome talk about
responsible disclosure by David Kriesel who found bugs in Xerox's compression
algorithms:

[https://media.ccc.de/v/froscon2015-1524-lies_damned_lies_and...](https://media.ccc.de/v/froscon2015-1524-lies_damned_lies_and_scans)

------
8_hours_ago
This could be an acceptable interview question for Javascript developers, but
from the SO question it looks like the interviewer screwed it up:

 _My answer was that it 's impossible. They said nothing is impossible. It
happened 2 weeks back, but I'm still trying to find the answer._

The interviewer should have gone into much more depth instead of (presumably)
marking that question as failed and moving on. This was a perfect opportunity
to find out more about the interviewee's knowledge of Javascript instead of
whether they immediately knew the answer to a trick question.

The interviewer could have asked about the difference between "==" and "==="
operators, which any experienced Javascript developer should know at least a
little about.

Then they could have asked if the interviewee knows how "==" converts types
before comparing them, and find out if they know that it uses .toString() and
.valueOf().

Then the interviewer could have asked about if those functions can be
overridden, and how that can be done.

At this point, the interviewee's eyes may have lit up and they may have been
able to solve the original question.

This approach would have given the interviewer information about the
interviewee's knowledge of: "==" vs "===" operators, .toString() and
.valueOf() functions, function overriding, and object variables. Instead the
only knowledge that the interviewer learned was whether the interviewee had
seen a similar problem before or was able to immediately recognize the answer.

~~~
lhorie
> would have given the interviewer information about the interviewee's
> knowledge of: "==" vs "===" operators, .toString() and .valueOf() functions,
> function overriding, and object variables

Sure, the interviewer could have spent some more time to lead the interview in
a more productive manner, but at the same time I'm left wondering: what does
the interviewer get from answers to those questions? Do the answers say
anything meaningful about the candidate's ability to write code (other than a
weak-ish probably-can-code/not-a-coder signal)? What about ability to test?
Design? Function as a team member? IMHO, the question wastes a lot of time
building up to an aha moment, while only getting a glimpse of the candidate's
ability to memorize various bits of trivia that are easy to google.

~~~
rmrfrmrf
I actually see two red flags based on the candidate’s response, so I’d argue
that this answer is rather telling.

1) The candidate demonstrates a lack of intellectual curiosity (and maybe even
common sense) when they say “that’s impossible!” and move on.

2) The candidate attempted to pass off their (inaccurate) assessment as fact
without even a shred of self-doubt. Colleagues like this are infuriating to
work with.

~~~
threatofrain
But do you actually think you have found an effective measurement device for
intellectual curiosity, persistence despite failure, or ability to examine
personal errors?

If we are trying to measure some kind of mental ability as a predictor to work
performance, one might question whether interviewer ability to extract such
deeper insights from these questions is actually more effective than a g test.

~~~
somestag
You can criticize any interview technique by questioning whether it can
_really_ effectively measure <X>. The answer is always no, and even if it were
yes, you can go on to point out that <Y> is also important and is not
effectively measured.

I would probably not give this question in an interview, but if I did, I'd
care a lot more about how the interviewee reacted to it than about getting the
right answer. The people I want to work with are people who respond to weird
questions with curiosity, not with guesses and a lack of followup. For a
question that presumably would only take a few minutes to ask, it's decent
enough. A bad question would be one that by design gives no information (or
worse, gives misleading information), and this question does better than that.

Am I guaranteed to learn about their curiosity? No. In particular, candidates
who are very nervous are more likely to clam up than start teasing out the
details of the question. That's unfortunate, but hopefully this isn't your
_only_ interview question so there are still other opportunities for the
candidate to show their stuff.

------
DoofusOfDeath
The problem is somewhat underspecified without us knowing the programming
language, and (perhaps) the data type of 'a'.

~~~
FLUX-YOU
The question tags indicate javascript

~~~
DoofusOfDeath
Sorry, my mistake. I assumed that the excerpt in HN was sufficient to
understand the question.

(Or if you're saying that HN is where I'd find the "javascript" tag, I'm
somehow not seeing that in my browser.)

~~~
FLUX-YOU
The tags are on the stackoverflow question

------
brndnmtthws
Please don't ask trick questions in interviews. It's never a good idea.

~~~
cle
Disagree. If you're a web developer, knowing these subtleties could prevent
major and time-consuming bugs. The best engineers I've worked with know a
ridiculous amount of these kinds of "tricks"\--that's a big part of what makes
them the best.

~~~
pmiller2
This type of information about the candidate can be gotten in a much more
evenhanded way by rephrasing the question: What's the trickiest bug you've
ever had to fix, and why? Follow up as appropriate with specific questions
about the actual bug they solved.

~~~
Stratoscope
I'm not very fond of questions in the form "What's the (trickiest|best|worst)
(bug|problem|code|thing) you've ever (fixed|written|seen)?"

Other examples are the classic "What's your greatest strength?" and "What's
your greatest weakness?"

These are all recipes for brain freeze. If you ask me a question like that
I'll probably think of something, but then I'll ask myself, "But was that
really _the_ best/worst/trickiest? Maybe there was another bug that was even
trickier, or another strength/weakness of mine that's greater/worse than the
one that just came to mind."

You can avoid that somewhat by leaving out the request to name the most
extreme case: "Can you tell me about an interesting bug you fixed?" Then I
could just pick one and start talking about it. Perhaps even better, ask about
an _embarrassing_ bug. Those may be the easiest to remember.

Maybe it would be that election results map that started turning states red
when CNN was turning them blue? And how the bug snuck in even with three
people reviewing the code change? And we could talk about what went wrong and
how code reviews don't guarantee correct code. All kinds of possibilities for
interesting discussion there.

------
whack
I was just about to laugh at JS, when I realized you can do the exact same
thing in Java also. a.equals(1) && a.equals(2) && a.equals(3) can evaluate to
true, if you overload the equals method with a particularly dumb
interpretation. I believe the same principle will also apply to any language
that supports operator overloading, such as C++.

~~~
mkup
in a pure C, without operator overloading and threads:

    
    
      int aa = 0;
      #define a (++aa)
      if(a == 1 && a == 2 && a == 3) {
        printf("pff");
      }

~~~
adrianratnapala
Well done. Whileone forgets evil macros are, we often forget how versatile
they are in that cause.

That said, I feel that in practice I have to worry more about this strange
hidden behaviour in C++ and Python than in C and JavaScript. And even Python
is not so bad if you stick to the standard libraries.

~~~
chias
Until you start playing with ctypes, where you can change the values of
constants.

In Python 3:

    
    
      >>> import ctypes
      >>> ctypes.memmove(id(5)+24, id(23)+24, 8)
      >>> 2
      2
      >>> 3
      3
      >>> 2 + 3
      23
    

Or, similarly for Python 2

    
    
      >>> import ctypes
      >>> ctypes.cast(id(4),ctypes.POINTER(ctypes.c_int))[4]=5
      >>> 2
      2
      >>> 2 + 2
      5

------
billconan
what's the point of this kinda of interview question?

~~~
lucideer
I'd normally be extremely critical of pointless tech interview questions, but
this one is excellent.

It tests both debugging skill (not taking innocuous code for granted) and
defensive programming (writing robust code that won't be affected by
environment).

The obvious example of the latter on Javascript is being aware of how closures
and scope work and avoiding global namespacing. If you're even vaguely aware
that the kind of trickery in the SO question is a possibility you're much more
likely to practice safe coding in that context.

~~~
FLUX-YOU
>but this one is excellent.

Not really. You'll give the impression this quality of code is part of
production code and send them running for the hills.

~~~
mark-r
Do you seriously think anybody would confuse this snippet for production code?

~~~
zaphar
You've obviously never seen the kinds of production code that I have. This
example is clearly distilled down but manifestations of the cause can be found
in many different languages and I've encountered quite a few of them in my
day.

That said I wouldn't really consider this a good interview question.

~~~
protomyth
Check me on this one. What if this is some absurd way to do a series of
process steps where the a == 1 checks if you can do step 1 and then executes
step 1 with a being set to 1 on success and 0 on failure thus allowing the &&
to go to the a == 2 comparison which handles step 2. This continues with the
rest of the line. Its just psycho enough to be plausible in a truly
dysfunctional way.

~~~
zaphar
I have encountered code written by people just psycho enough to think that's a
clever way to handle just that scenario. They were not wrong it was indeed
clever. It was also terrible.

~~~
protomyth
The sad part is I too can see someone who needs to do batch processes reading
about short circuit evaluation and having this "amazing" idea for a framework
that would look exactly like that if. Its moments like those that make me wake
in a cold sweat.

