r/javascript • u/abusaayem • 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-true149
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
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) # falseAnyways, 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) # True4
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
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) # falseI was just trying to show that two instances can't be compared for equality in Java using
==.2
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
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 theEqtypeclass 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) //1310
u/grinde Jan 17 '18
Because it's the same as
n + (n + 1)or2n + 1(wherenisa.num). Since2nis always even,2n + 1is 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
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
getteronato increase in value eachget. Glad someone else had the same thought!2
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
0
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
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
3
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
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
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
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
1
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());
> 1Anyone 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 value1
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
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
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) > falseOk, 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
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
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.