Hacker News new | comments | show | ask | jobs | submit login
Can (a ==1 && a== 2 && a==3) ever evaluate to true? (stackoverflow.com)
180 points by _nalply 6 months ago | hide | past | web | favorite | 147 comments



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.


> 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.


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.


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.


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.


Questions like this don't tell much about a candidate's ability to design, write, and test maintainable code, however they do give information on a candidate's specific area of knowledge.

These questions are useful if you are looking for an experienced X programmer who can immediately start being productive in an X code base. While the original problem is definitely a trick question, I don't believe that any of the individual pieces of knowledge required are merely "bits of trivia" for an experienced Javascript developer.

It's the interviewer's responsibility to know what areas of knowledge are required for a role, and how important it is that a candidate is familiar with them. Memorizing the intricacies of "==" vs "===" may not be important, but I'd expect an experienced Javascript developer to know something about it.

What about ability to test? Design? Function as a team member?

Those skills are much harder to test for so most companies ignore them during the interview process and instead focus on attributes which can be tested for, and accept that the process is not 100% reliable.


I just sent the SO-link to a friend remarking: "...but I think if I were asked this in an interview, I'd just walk out"

Asking only this question, without using the various other avenues one could explore from there, like you suggested, makes me actually question the competency of the interviewer. That is of course the competency in finding suitable applicants for the role they want to fill, assuming they're not looking only for people writing quirky 5-liners all day long which exploit some weird language behaviour.


Sigh, the sad state of dev interviews in a nutshell.


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++.


in a pure C, without operator overloading and threads:

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


Heh, my knee-jerk reaction was to complain that that's undefined behavior but for once it's not! The logical operators && and || are defined to establish sequence points due to their short-circuiting evaluation.


Here's a Common Lisp version:

    (let ((b 0))
      (symbol-macrolet ((a (incf b)))
        (and (= a 1) (= a 2) (= a 3))))
For those not familiar with them, symbol macros let a symbol be expanded to an arbitrary expression, kinda like a clean version of the C preprocessor.


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.


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


Heh nice, that's clever.


it's essentially an explicitly clocked data race. evil.


Even if you were using the [identity] equality operator in Java, since the question asks if it could "ever evaluate to true", the answer is also yes if another thread is updating the var during the if check.


Just tried it in C with a thread, which did work like you say.

  int a = 1;

  void *brute(void *vargp){
    while(1) {
	a = 1; a = 2; a = 3;
    }
  }

  int main(){
    pthread_t tid;
    pthread_create(&tid, NULL, brute, NULL);
    while(1){
        if( a == 1 && a == 2 && a == 3 ){
	    printf("woo\n");
	    return;
    	}else{
	    printf("fail\n");
        }
    }
  }


This could perhaps happen within async functions when you have await's interleaving. Or in server-side Meteor code because of fibers. But not in the browser in non-async functions because JavaScript is single-threaded, especially inside a compound expression.


This is a good answer to the terrible question. Nice.


Arguably C++ is worse:

    class Equal {
        public:
            template <typename T>
            bool operator==(const T& eq) { return true; };
All kinds of equality are possible.


In Perl 6, we can do much the same without all of the boilerplate.

    class a {};
    multi sub infix:<==> (a $a, $b) {
        True
    }
    if a == 1 && a == 2 && a == 3 {
        say "true!"
    }
If you wanted to make an actual iterator out of `a`, you could do:

    multi sub infix:<==> (a $a, $b) {
        ++(state $) == $b
    }
In that case, `a` would equal 1, 2, and 3 in that order. 5 is right out.


Or you could just use a junction:

    my \a = any(1, 2, 3);
    if ( a == 1 && a == 2 && a == 3 ) {
        say "OMG quantum superposition!!!";
    }
For those wondering what's going on: https://docs.perl6.org/type/Junction.html :-)


It's also trivial in C# to overload the == operator. The following works in C# Interactive (the Visual Studio REPL).

  class A { 
    public static bool operator ==(A a, int b) => true; 
    public static bool operator !=(A a, int b) => false; 
  }
  var a = new A();
  if (a == 1 && a == 2 && a == 3) Console.WriteLine("This works");


The only thing bad about that is that there's no check whether equality is symmetric. As written it does make sense if you interpret it as "<=" or ">=".


The more worrisome thing about equality in Java is that there are integer values for which

  a == a
is true, while

  a + 1 == a + 1
evaluates to false.

(edit: precision)


I assume you are referring to the java.lang.Integer box caching situation, which is indeed shitty. However as you've written it, that will always evaluate to true, as it unboxes, adds 1 to each side, and compares the int values, not the references. To get what I assume you are talking about, you need something like:

    Integer b = a+1;
    Integer c = a+1;
    b==c
Which by default returns true for a=126 but false for a=127. A bad situation for sure, but thankfully pretty much every static analysis tool will spot that.


Yes, you're right. Thanks for correction.


You can write a type in Haskell with your own crazy instance of Eq but you can't hide the mutation from the user without something like unsafePerformIO.


The question doesn't use a.equals(1) it is a==1 which is not the same and does not use the equals() method in Java, so it can't be overridden. It compares primitives or variable references only.

However, it is possible for that statement to evaluate to true with threads if you manipulate the a at the right times.


Sure, but it's clear that you're overriding a method. In Js you're using an operator for which there's no explicit overloading, and instead you're exploiting 'coercion' rules.


Should be pretty easy to do in C# as well.

    private int _a;

    public int a { get { _a++; return _a;}}


Also likely to apply in any late-bound language where operators are implemented by messaging e.g. Ruby:

    a = Object.new; def a.==(b); true; end
now a == b returns true for all b.


and a particularly dumb interpretation can be

return true


Yes, while it may be fun to change values in a careful way, this is by far the more interesting one.

The equivalent of "return true" is so powerful (or, alternatively, is so parsimonious in its use of power, depending on your perspective), you can even make it work in Haskell, where these mutation tricks don't work, because you can declare a newtype with a custom declaration of == that is just "true".


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.


> Very few people are going to pass that test.

Agree that this isn't a reasonable "normal" programming mistake to run into, but I think the question may be used for seeing how candidates approach a problem that they don't know how to solve.

I doubt the interviewers are looking for someone to get this question 100%, and more likely looking for how candidates would deal with a problem they haven't been confronted with before that seems unsolvable. Does the candidate just say it's impossible or a trick? Or do they double down and try to think of what could possibly cause this and offer up some possibilities?


That’s the ideal, but they are typically thrown out when you have ten candidates to interview and so becomes one more binary filter.


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.


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.


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


Python supports operator overloading, js doesn't. Expectations are different.


I'm not familiar with threads in javascript, but the expression could be true (though mighty hard to bring it about) in many multi-threaded languages.


JavaScript is a single-threaded execution environment with an event pump. When people talk about asynchronous actions like in Node.JS, they really mean doing non-JavaScript things in another thread and waiting for an event to arrive back. For example, load this file, and put an event on the queue when it's completed loading so that I can process it. In this way, you can queue multiple files to be loaded at once, even though only one can be processed by the JavaScript code at one time. This generally works out OK, because many systems are effectively IO bound and not processing bound.


Sure, that exact code is unlikely to be an honest mistake, but couldn't it be a distilled example of much more complicated code where that mistake -- unexpected or undocumented sideeffectiness -- was made honestly?


> 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.


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.


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


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";
  }


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");
    }


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!";  
  }


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.


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


I'm not defending the interview question, but it's a valuable trait if someone can take the evidence of a logic-defying test run and ask themselves "This seems impossible, how could it have come about?" rather than "This is impossible, it must represent a hardware defect." -- or "This is mysterious and impossible but I just perturbed it enough to make the mysterious effect go away."

IMO this interview question is not horrible, especially if the answer(s) given are taken as a larger context of evaluating someone. If the candidate the interviewer responded "no, can't evaluate to true", then a good follow up might be "in fact it can! can you think of why/how?"


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.


>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.


If I were hiring, I'd be looking for a candidate who makes considered, well-researched-and-thought-out judgements, not one who runs for the hills based on speculating that a few characters of a conditional might be representative of a company as a whole.


Could you maybe use some considered, well-researched-and-thought-out judgements regarding the kinds of questions you ask so that candidates can get a better feel for the demands and level of quality you put into your code instead of intentionally asking lower-quality questions which give you arguably little insight into how candidates actually code?


The quality of the question is subjective. My opinion of its quality is well-researched-and-thought out - you're entitled to disagree but that doesn't nullify the fact there's thought behind it.

You were making out that a candidate would "run for the hills" based on a wild extrapolation about the company's production code - I was responding to that point, which is quite independent of the quality of the question.


Technical interviews are two-way assessments. If you're not going to put your best effort by representing the work fairly through the technical interview, it certainly says something about how you view and respect potential candidates' time and maybe it indicates the quality of code you run.

I have nothing else to go on unless you have public repos. I personally don't think it's a wild extrapolation based on the code quality compared to interviews I've gotten and I quickly reject companies that don't put forth fair tests. At worst, I'm wrong about the code quality, but I'm still selecting based on bad interview questions, which I'm perfectly fine with and I think more people should do if only to generate some kind of rejection signal to get interviewers to stop asking mundane questions like this.

It's not like companies don't also reject candidates for equally small bullshit or extrapolating conclusions about candidates based on the interview anyway.


> Technical interviews are two-way assessments. If you're not going to put your best effort by representing the work fairly through the technical interview

Interviews (technical or otherwise) are an opportunity for both parties to ask questions and discuss what each is looking for. In that sense, interview questions should ideally elicit discussion. This gives the interviewer an opportunity to assess how the candidate approaches problems and gives the candidate an opportunity to explore their perspective on those problems (again, in discussion -- dialogue)

I don't think the questions need to be "representative" as you say. The primary purpose is not too represent the company, it's to allow the candidate to best represent themselves. I'd actually say distilled problems may do this more effectively and efficiently than ones "lifted" from prod.

Also, in terms of putting "effort" into interview questions, lifting from prod seems much lazier tbh.

> I have nothing else to go on unless you have public repos

I've generally just asked, which has in my experience been received as a normal request.


Do you seriously think anybody would confuse this snippet for production code?


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.


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.


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.


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.


Well, given some of the code I have seen, I would have a sneaking suspicion that clean code was not the hallmark of this company's source code. They are also probably asking these type of questions because they use some of these "cool techniques" in their code. I then start having a flashback to some code in 98 that I had to debug at 2AM to get the damn batch job out by 6AM that turned out to be some really "clever code"[1]. Yeah, I might checkout early and run for the parking lot.

1) said right there in the comment, but not why or how it was clever or what it really did


IMO, a good interview question should reflect daily work.


If this were the only code they showed you, then you can consider that a fail on their part. Remember that an interview goes both ways.


If they want me to assume this kind of code would never be in prod, then they can assume I know how to write code and we can dispense with the technical interview altogether.


If you provide candidates a live debugger, I'd say this tests debugging skills (which I think is important to test.)

I'm not sure what this tests if it was on a white board.


You're right, and this wouldn't test debugging skills to that extent. But even with a live debugger you need an appropriate problem.

In terms of whiteboard/paper questions, the fact this touches on the mindset/approach to debugging makes it far better than a lot of other whiteboard/paper questions I've seen.


No, this is a really poor trivia question for JavaScript. The question itself is lacking an important detail: what is the type of a? As presented, I think it would be safe to assume a is a number and thus it cannot possibly true. However, if a can be an arbitrary object, then there apparently is some hacky incantation that can make it true.


You seem to be thinking of it as a yes/no/definite answer question. Interview questions should elicit discussion and deconstruction of the subject. Through this you can get an impression of how a candidate approaches the question.

Your breakdown being a good example of such discussion.


This is a terrible interview question. It is an unrealistic scenario, should never be in production code, and does not offer any additional information from the candidate.

Please never ask this on any interview loop, thanks.


Interview questions are rarely about the code itself, but the discussion about the code. I think this is what people miss when they say "I'll never actually need to do X". Yes, but I want to see how you can take clear requirements and implement them in code. Or I want to see how you'd approach a seemingly impossible behavior happening in production. As a piece of trivia the question isn't great but as a "how does a person debug some totally unexpected behavior that requires somewhat deep knowledge of the language to comprehend" it is a great question.


I think it would be more appropriate to ask:

This conditional evaluates to `true`, but how?

If you first ask, 'Is this possible?', then most of us, who have long forgotten terrible coding standards, would say no, out of hand. I would have thought the interviewer was testing to see if I was an idiot.

I find once I resolve myself to knowing that the bug is possible, then I can find and fix it.


I find this kind of question quite interesting in a somewhat unfair way. When something highly unexpected is presented, it really makes the candidate think out of the box. I can for example immediately think of several weird cases (overloaded operators/implementation of == or &&, another thread trying to increment it at the same time, strange type coercion rules, running inside a debugger etc) and to me, as an interviewer if I heard of a novel answer, this shows the creativity of the candidate.

But again I concede that this is totally unfair. Not everyone can immediately think out of the box at a moment's notice, especially during an interview which can be quite stressful. I certainly wouldn't place a lot of weight on those kind of questions; if the candidate surprised me with a novel answer, that would be the icing on the cake.


> Not everyone can immediately think out of the box at a moment's notice, especially during an interview which can be quite stressful.

Yup. This is sometimes a skill you want to test for - I have had a job where I would occasionally get paged at 3 AM to diagnose and fix novel problems in parts of infrastructure that I hadn't previously interacted with, for a high-frequency trading company where every minute of downtime had a financial impact. If you're hiring for that sort of thing, asking people if they can figure out stupid problems under time pressure and in a high-stress situation is exactly what you want to select for.

If you're hiring someone to sit at their desk, write code, and go home after 8 hours, where "time-sensitive" problems have their response time is measured in days and not minutes and where there's plenty of time to Google for similar situations or try to reproduce the problem in a test environment, responding to weird questions on short notice with someone staring at you until you figure it out is a much less relevant skill. And I think most tech jobs fall in this category. Ideally, give them interview problems where they can go home, get some sleep, drink some tea, and figure out the answer in the morning. I've done a bunch of hero work on O(minute) timeframes, but my actual quality work has always taken days of thinking about the problem quietly.


There is no point. The point of interviews is to find engineers that can do the work. This question doesn't further that goal.

It "works" because we've been trained to laude pointless BS as if it were somehow valuable. The interviewers themselves had to answer some BS questions, therefore they perpetuate it. Candidates don't reject the questions because there's no quicker way to fail an interview than to balk at an unfair question.

Ask yourself: Now that you know the answer, are you a better programmer? Truly?

If becoming a better programmer were that simple, anyone off the street could do it.


Finding someone who knows the answer isn't nearly as valuable as finding someone who can figure out the answer.


And figure it out with the clock ticking, a gun to their head, and a hundred thousand dollars in a suitcase.

Random outcomes FTW.


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.


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.


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 ;


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?


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... for a related bug.


It would certainly be a violation, as the algorithm to evaluate == is rigorously outlined in the language specification, specifically here: https://www.ecma-international.org/ecma-262/8.0/index.html#s...

This algorithm does not describe an optional caching step to speed up/short-circuit the procedure, and so the optimization you describe would lead to non-spec-compliant behaviour.


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.


>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.


  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


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.


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


I've seen something similar to the "junction" example someone mentioned in Perl 6 used, where a function that (with some justification) would allow multiple passwords for a given user to be valid set up a value that would compare equal to multiple things, then check in a single == with the password whether it was valid.

I eventually nuked it and replaced it with the obvious for loop, which given as I also got to nuke the implementation of the class in question, meant a significant net reduction in line count, one less file in the repo, and one less wart in the code for new developers to stumble over.


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) {
    ...
  }


In this case they should use bitfields and bitflags.


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.


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.


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.


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?


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


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.


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).


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.


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!


yes in a concurrent program


Is concurrent javascript a thing?


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 :-)


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.


You cannot overload operators in javascript


Sort of, you're thinking along the right lines, look at the stackoverflow answer.


No.


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


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


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.


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


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.


In this case I think you can since I think && is a sequence point.

a + a on the other hand would be undefined.


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


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.


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


Which reminds me of the perl jam (29 min) https://media.ccc.de/v/31c3_-_6243_-_en_-_saal_1_-_201412292...


There is a slide in there where he makes something like 5 mistakes, and yet most people think he knows what he is talking about.

I will grant that he found a problem where DBI and CGI was used together carelessly.

I think I remember him saying that perl comes with DBI, even though it has never done so. Also CGI has recently been taken out of the core distribution. (Most people have been recommending to not use it since around the year 2000.)


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


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...


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


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.


spoiler: yes in js it can

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


you could also overload the && operator for extra confusion


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


oops i missed that bit


yes, at very high speeds


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


Why? I'm curious because sometimes I use a "trick" question (trick in quotes because this really isn't a trick question either) to gauge someone's ability to think on their feet. A "trick" question being one I'm fairly certain there's no answer to floating around and which requires some thinking. The goal should never be a pass/fail did they know the trick question, but someone who can think on their feet and work through one is more appealing to me than someone who throws in the towel.


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.


"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."

Nah, no way. I work with some great engineers and they do not do "tricks" in their code. You write clean code that works within known conventions and patterns, so that it has long term maintainability. If you need "tricks" like this, then you're probably neck deep is some trash code looking for hail-marys to save you from yourself by causing side effects that you desire in the short term.


Nobody should intentionally write code like that. But being able to quickly identify code that unintentionally causes strange behavior (and being able to avoid it) is hugely valuable.


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.


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.


I generally agree you shouldn't ask pass/fail "trick" questions, but in most domains there are some questions that can tell you a lot more about someone than it might seem to an outside observer. For example, in an android domain interview, I've asked people to make a view blink onscreen. It's totally fine if they roll an implementation on the spot (and it's an easy question anyone can handle), but someone seasoned with the framework or who's read a lot of framework sources might know there's an undocumented feature of LayoutInflator that builds blink layouts if it encounters a <blink> tag while parsing layout xml. At least to me, that extra info is valuable. I'm sure there are analogs in for example C++ about quirks of the language that change with and without RTTI or exceptions etc that would tell you a lot about how much real experience someone has working with a given tool.


Others seem to misunderstand your point. Essentially you want someone with deep knowledge. To share an example... "Deep C" - by Olve Maudal [0]. It isn't about writing bad code - it's about understanding how the code will compile/run, how to avoid potential issues, and how to avoid similar issues that might occur that stem from that same understanding of how the code will compile/run.

[0] https://www.slideshare.net/olvemaudal/deep-c/9-What_will_hap...


Maybe your problem is you hired developers that write code with tricks and gotchas.


Read more carefully. I would never hire a developer who would write code like that. I would hire a developer who can quickly identify such subtle mistakes, and fix/avoid them because of that deep knowledge.


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


The question tags indicate javascript


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.)


The tags are on the stackoverflow question




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact

Search: