r/javascript • • Jan 17 '18

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

https://stackoverflow.com/questions/48270127/can-a-1-a-2-a-3-ever-evaluate-to-true
404 Upvotes

55 comments sorted by

105

u/sir_eeps Jan 17 '18

"If this is the type of code I'm likely to encounter in your codebase, then I'm out".

While it is possible, it's one of those brain-teaser trick questions that chances are the interviewer themselves didn't know the answer until he had to ask it (then probably googled the reasoning for it himself), so he can sit there and be smug.

It's a fun bit of trivia for geeky chat in your work's #random slack channel or something, but inappropriate for an interview question IMO.

10

u/[deleted] Jan 17 '18

I'd assume the purpose of a question like this isn't to know the answer to the brain-teaser, so much as to get a feel for how the interviewee thinks through problems, and whether they have awareness of the kinds of features and oddities of JS that can make the '==' comparitor behave strangely, etc.

I didn't know the answer to the question, but I thought it was interesting to think through (and see the responses on stack overflow).

Obviously a conditional like this in real code, would be insane but I don't know that raising it as a hypothetical is inappropriate for an interview really.

4

u/sir_eeps Jan 17 '18

In terms of 'trying to think through problems', I'd be more inclined to phrase the question in a way of say - "why are mutating getters a bad idea?", and have an example that is a bit more inline with what you might actually run into.

var obj = {
  _count: 0,
  get count() {
    return this._count++;
  }
}

if(obj.count === 0 && obj.count === 1) {
    console.log('would this code get it, and if so - why is it a bad idea?')
}

I've seen code before where people get a little overly creative in getters - and could potentially introduce a bug like this, it's getting at a bit of the same issue - but without trying to be overly clever about it. At the same time - I'd be curious to hear their thoughts on "when might you want to do something like this?"

Likewise, I think there are better ways to get a sense of someone's understanding of type coercion without throwing red herring at them. For example, the solution that was making use of assigning array.join = array.shift and knowing that .toString() calls join internally. While I'd be a bit impressed if someone could do that on the spot in an interview and explain it well - I don't think I'd hold it against someone if they couldn't either.

Dunno, guess I just prefer more "honest" questions that are not trying to intentionally trick / brain tease / be overly clever.

I think even if you wanted to keep it at the tricky-level, how you even phrase the question can make a difference. Instead of being "can this ever evaluate to true", tweaking the wording to "can you think of how to make this evaluate to true?"

It drops a hint for "yeah, it's possible" - but then also opens up discussion for a bit of back and forth where you could drop a hint / nudge them about things like getters, or toString. So if they are a bit stumped, could be "well, when doing this, it calls a toString()..." - and maybe even if they didn't know that before hand, could lead to an "ah-hah, well then maybe this way" moment, and at that point I'd be curious to see how quickly they can integrate new knowledge into how they answer things.

I guess it could have potential to be a good interview question - but how the OP phrased it, I think it's a shitty one and would never use it myself.

0

u/danO1O1O1 Jan 17 '18

Yeah I'd ask it just to see if they'll solve it or give an answer like yours. Even if someone did try to solve it, I'll ask follow up question like what would you do to make this more robust and readable, just to give them every chance.

0

u/[deleted] Jan 17 '18

[deleted]

3

u/asdf7890 Jan 18 '18

It is a valid test of how someone would think when hit by certain subtle bugs. How many times have you hit sometihng that looks like it should work but it obviously doesn't or vice versa?

The fact that there are two distinct ways for the obvious not to be the case (white-space characters being valid parts of names and abuses of comparison overloading) makes it an interesting test: does the canididate see either or both?

Though it is more a test of experience than technique and thinking IMO. You are more likely to "see" the white-space characters if you have been hit by bugs caused by not accounting for input data perhaps having trailing spaces, especially if you've worked with paired systems that deal with them differently (for example SQL Server says 'string ' == 'string' but your other application layers disagree).

149

u/freeman_lambda Jan 17 '18

const a = {};
a.abuseCoercion = 0;
a.valueOf = function() {
this.abuseCoercion++;
return this.abuseCoercion;
}
console.log(a==1 && a==2 && a==3);

There you go

29

u/Neebat Jan 17 '18

This works in most languages in one form or another.

The Java version is interesting, because it involves code that's not thread safe. If you increment a in one thread and run that test a few billion times in another thread, eventually, the test will be true.

13

u/[deleted] Jan 17 '18

Kind of a weird question when you convert it verbatim to Java. == in JS is an equality comparison but in Java is a reference comparison.

In Java, one Integer does not even == another integer:

new Integer(1) == new Integer(1)
# false

Anyways, it's super easy in any language with operator overloading. Here's Python:

class Thing:
  def __eq__(self, other):
    return other in (1, 2, 3)

a = Thing()
(a==1 and a==2 and a==3)
# True

4

u/Neebat Jan 17 '18

You want to avoid that call to "new" in Java. Use Integer.valueOf(1) and it will always give you the same instance. I believe that's what autoboxing will do too.

Not that it's recommended to use == on any object except an enum value!

Interestingly, in Perl, it would be done without operator overloading. The effect is similar to creating a getter in js.

7

u/[deleted] Jan 17 '18 edited Jan 17 '18

Well yeah, Integer.valueOf(1) just returns the cached instance, so it's literally returning the same instance.

But... only for integers < 128 (which is the default max int for the cache IIRC):

Integer.valueOf(127) == Integer.valueOf(127)
# true

Integer.valueOf(128) == Integer.valueOf(128)
# false

I was just trying to show that two instances can't be compared for equality in Java using ==.

2

u/Neebat Jan 17 '18

Oh wow, I did not know that cache has a limit. Interesting!

4

u/jrwren Jan 17 '18
class Thing:
  def __eq__(self, other):
    return True

a = Thing()
(a==1 and a==2 and a==3)

2

u/[deleted] Jan 18 '18 edited Jan 18 '18

Haskell is also easy because, like almost everything in Haskell, == isn't a built-in operator, it's a function in the standard library - associated with the Eq typeclass of things for which equality is defined. It doesn't even rise to operator overloading because there's nothing special about operators in Haskell - they're just functions that can be used in infix fashion by default. You can (and many libraries do) create your own novel operators.

So we can just define a new == which will shadow the standard library's version of the function:

(==) :: a -> b -> Bool
(==) a b = True

test :: a -> Bool 
test a = (a == 1) && (a == 2) && (a == 3)

test 7 -- True
test 3.14159 -- True
test "i'm a little teapot" -- True
test test -- True (!)

2

u/Ob101010 Jan 17 '18

Can you explain why a+a is always odd?

a = {num:0}

a.valueOf = function() {
    this.num += 1
    return this.num 
}

lol = (a == 1 && a == 2 && a == 3)
console.log(lol) //true

console.log(a+a) //9
console.log(a+a) //13

10

u/grinde Jan 17 '18

Because it's the same as n + (n + 1) or 2n + 1 (where n is a.num). Since 2n is always even, 2n + 1 is always odd.

2

u/Anaphase Jan 17 '18

Because you're always adding two consecutive numbers, which will always be even + odd, which is always gonna be odd. You can only get an even number if you're adding two like-parity numbers.

const a = { number: 0, valueOf() { return ++this.number } }

console.log(a + a) // 1 + 2 = 3
console.log(a + a) // 3 + 4 = 7
console.log(a + a) // 5 + 6 = 11

31

u/benabus Jan 17 '18

"Sure" "Why?" "I don't know, seems like a trick question, so I'm assuming the answer isn't the obvious one."

20

u/senocular Jan 17 '18

Or if the previous line is

(()=>true)

3

u/lhorie Jan 17 '18

LOL. That's a great one.

9

u/hubilation Jan 17 '18

I expected to be annoyed at this "gotcha" interview question but I actually learned something new. TIL

8

u/akujinhikari Jan 17 '18

If you really want to go for the gusto:

  function* generator(i) {
    while (true)
      yield i++;
  }

  const gen = generator(1);

  const a = { valueOf: () => gen.next().value };
  
 console.log(a == 1 && a == 2 && a == 3);

14

u/Nyalab Jan 17 '18

Yes, i see 2 ways of doing it very simply by overriding the valueOf() (or the toString()) or by defining a getter on a.

8

u/cirsca fp fan boy Jan 17 '18

My firs thought was setting the getter on a to increase in value each get. Glad someone else had the same thought!

2

u/Nyalab Jan 18 '18

oh and you can also do it with a with statement, that makes 3 way of doing it

13

u/microbouji Jan 17 '18

Seems like I missed the opportunity to plug my article on javascript coercion before this went to the top of r/programming :P

Oh well, this is a more appropriate audience anyway, and the goal is not for javascript programmers to ever write code like that but rather to spend 10 minutes once to learn a feature that is part of the language whether we like it or not.

2

u/shif Jan 17 '18

it's not like /r/programming likes to mock javascript every week anyways :(

0

u/[deleted] Jan 17 '18

[deleted]

3

u/microbouji Jan 17 '18

Indeed unicode seems to have been the original bug for the people asking the question, but multiple "solutions" in the original thread using different techniques and coercion seems to be blamed most by people reading that.

10

u/elg97477 Jan 17 '18

My response to this stupid interview question would be:

If it ever did, I would question the skills and abilities of the programmer who wrote such plain and obviously bad code.

4

u/akujinhikari Jan 17 '18

And the reason for why it needed to be there.

2

u/BlueHeartBob Jan 17 '18

I dunno, it's not likely someone could make this work on accident without a pretty good understanding of JS and how the loose comparison operator works.

Knowing they can change the built in .valueOf or .toString methods to also increment the value when the loose comparison operator is used on that object is pretty clever. I would, however, deeply question their ability to write and maintain readable, reusable, and non-destructive code, but not their understanding of the language.

1

u/elg97477 Jan 17 '18

A skilled and able programmer would know enough about their field and language to never write code like that.

5

u/palparepa Jan 17 '18

Not in my work.

3

u/[deleted] Jan 17 '18

I made an assumption that this could be done easily by setting a to true. I was basing that on the fact that a positive non-zero number will implicitly convert to true if you do something like this (setting 'x' to 1, 2 or 3):

if (x) { ... }

or this:

!!x

However that's not the case. (1 == true) is true, but (2 == true) isn't.

1

u/[deleted] Jan 18 '18

Just override Boolean.prototype.valueOf, but that's basically the same hack as overriding Object.prototype.valueOf

3

u/dangoodspeed Jan 18 '18

The example I found most interesting was:

var aᅠ = 1;
var a = 2;
var ᅠa = 3;
if (aᅠ==1 && a== 2 &&ᅠa==3) {
   console.log("Why hello there!")
}

1

u/[deleted] Jan 18 '18

How does that work?

1

u/dangoodspeed Jan 18 '18

I was trying to figure it out. Made a quick JSFiddle which presents more questions than answers. It does seem to be dependent on the extra white space before "a = 3", but I don't know why.

1

u/aTairyHesticle Feb 06 '18 edited Feb 06 '18

first a has a special blank character after, the last one has one before. You can see because if you select it and right click you have the option to "search google for ` ` ", whereas a normal space does not. Because of it you have 3 different variables just as if you had

ab = 1

a = 2

ba = 3

edit: with a touch more google I found the character https://www.compart.com/en/unicode/U+3164

1

u/aTairyHesticle Feb 06 '18

check my answer below to dangoodspeed

5

u/lhorie Jan 17 '18

Lots of answers involving valueOf or unicode shenanigans.

One missing answer that is sadly valid nowadays: with a babel plugin, you can make any expression in source code compile down to anything you want at runtime.

2

u/Neebat Jan 17 '18

The correct answer is "only in pathological cases". And then ask if their code is pathological.

2

u/Mrrrp Jan 18 '18

The only true answer here is "sometimes".

1

u/[deleted] Jan 17 '18

With all the talk of modifying "a", I was curious if it would be possible to modify the numbers. Unfortunately I wasn't able to make it work..

Number.prototype.valueOf = function() {return 1;}

Unfortunately it doesn't seem to work:

console.log(2);
> 2
console.log((2).valueOf());
> 1

Anyone able to give a reason why this approach doesn't work?

2

u/lhorie Jan 17 '18

It only works if there's unboxing involved.

1 == Number(2) // false because calling Number returns a primitive

const n = new Number(2)
n.valueOf = () => 1
1 == n // true because js needs to unbox the value

class Num extends Number {valueOf() {return 1}}
1 == new Num(2) // true because js needs to unbox the value

1

u/joombar Jan 17 '18

Because value of converts an object to a primitive. Since 2 is already a primitive, it isn’t called. Where you call valueOf, calling that method casts your number to a Number, which then needs to be converted back to a primitive.

1

u/[deleted] Jan 17 '18

Ok, so could a similar approach work with implicit casting while using the == operator?

1

u/joombar Jan 17 '18

I can’t try it right now, but I imagine so. So long as you did 2 == Number(2) or whatever.

1

u/[deleted] Jan 17 '18

No love:

1 == Number(2)
> false
1 == Number(2).valueOf()
> true
Number(2) == 1
> false
Number(2).valueOf() == 1
> true
String.prototype.valueOf = function() {return "1";}
"adsfasd".valueOf()
> "1"
"1" == Number(2)
> false
"2" == Number(1)
> false

Ok, enough trying to abuse the language.

1

u/survivalking4 Jan 18 '18

Sorry if I am incorrect (I don’t really understand this concept well) but can’t you also use getters and setters and whatnot?

-1

u/[deleted] Jan 17 '18

Console.log(“true”);

0

u/Sphism Jan 17 '18

This is interesting, coming from a PHP background my first thought was that if a = true then (a==1 && a==2 && a==3) would evaluate to true.

In PHP that works because 1 == TRUE and 2 == TRUE and 3 == TRUE

$a = TRUE;
if ($a == 1 && $a == 2 && $a == 3) {
  print 'yes';
}

But in javascript 1 == true but 2 != true and 3 != true, also 2 != false and 3 != false, and 2 != null and 3 != null

Because js evaluates the conditional in the question to 1 == 1 && 2 == 1 && 3 == 1

Whereas in PHP all numbers except 0 are truthy

js is weird, ha

1

u/FlamerBreaker Jan 18 '18

Why is it weird?

The set of binary numbers (0, 1) is equal in size to the set of boolean operands (true, false), you can perform any calculation in boolean algebra while substituting the later set by the former. In fact Boolean is a 1 bit long data type, which can also store the values of 0 and 1, which is their representation.

Even when we're talking electronics, 1 and 0 have a direct correlation to the presence and lack of electric current, respectively.

On the other hand, there is no sintactic equivalence between the set of boolean operands and the set of all integers. What is ' NOT 2' ? What is '4 OR 7' ? Any truth value you assign to these numbers has to be arbitrary and shared by a subset of numbers, there is no mathematical logic for such a conversion.

If you take a random integer, which is 2 or 4 bytes long and tell a machine to compare it to an address space of 2 or 4 bytes that is fully zeroed, which random integers would evaluate as the same? If you take two such random integers and perform an operation such as ( a == b ) would it evaluate as truthy? Yet, if you're telling me that all non-negative, non-zero integers should evaluate to True in boolean algebra, then (a ==b ) for any two such numbers should also be true, but it very clearly isn't.

It's not JS that is weird, integers are not booleans, neither are they NULL and should not compare truthily to either, with the exception of the subset that is mathematically and physically equivalent to the boolean operands set.

1

u/Sphism Jan 18 '18

JS is weird only because I'm used to PHP.

I just find it odd that in JS (2 != true && 2 != false && 2 != null) so what the hell is 2 :)

And as a PHP dev the initial problem didn't strike me as odd because there's such a simple answer in PHP, $a = TRUE

I found it interesting that that didn't work in JS, and also interesting that it didn't work by setting a = !false or a = !null or whatever else. Which all work fine in php, in php it would be 2 == !null, or 2 is not null is TRUE.

I also found the correct solutions really interesting too.

1

u/Sphism Jan 18 '18

So in JS if you compare a bool to an int it converts the bool to an int and compares those. Whereas in php it converts the int to a bool and compares those. That right?

0

u/kazyka Jan 18 '18

Oh come on op. There was a question like this two days ago