Thursday, January 25, 2018

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

Leave a Comment

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

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

30 Answers

Answers 1

If you take advantage of how == works, you could simply create an object with a custom toString (or valueOf) function that changes what it returns each time it is used such that it satisfies all three conditions.

const a = {    i: 1,    toString: function () {      return a.i++;    }  }    if(a == 1 && a == 2 && a == 3) {    console.log('Hello World!');  }


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

Answers 2

I couldn't resist - the other answers are undoubtedly true, but you really can't walk past the following code:

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

Note the weird spacing in the if statement (that I copied from your question). It is the half-width Hangul (that's Korean for those not familiar) which is an Unicode space character that is not interpreted by ECMA script as a space character - this means that it is a valid character for an identifier. Therefore there are three completely different variables, one with the Hangul after the a, one with it before and the last one with just a. Replacing the space with _ for readability, the same code would look like this:

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

Check out the validation on Mathias' variable name validator. If that weird spacing was actually included in their question, I feel sure that it's a hint for this kind of answer.

Don't do this. Seriously.

Answers 3

IT IS POSSIBLE!

var i = 0;    with({    get a() {      return ++i;    }  }) {    if (a == 1 && a == 2 && a == 3)      console.log("wohoo");  }

This uses a getter inside of a with statement to let a evaluate to three different values.

... this still does not mean this should be used in real code...

Answers 4

Example without getters or valueOf:

a = [1,2,3];  a.join = a.shift;  console.log(a == 1 && a == 2 && a == 3);

This works because == invokes toString which calls .join for Arrays.

Another solution, using Symbol.toPrimitive which is an ES6 equivalent of toString/valueOf:

let a = {[Symbol.toPrimitive]: ((i) => () => ++i) (0)};    console.log(a == 1 && a == 2 && a == 3);

Answers 5

If it is asked if it is possible (not MUST), it can ask "a" to return a random number, it would be true if it generates 1,2 and 3 sequentially.

with({    get a() {      return Math.floor(Math.random()*4);    }  }){    for(var i=0;i<1000;i++){      if (a == 1 && a == 2 && a == 3){        console.log("after "+(i+1)+" trials, it becomes true finally!!!");        break;      }    }  }

Answers 6

When you can't do anything without regular expressions:

var a = {    r: /\d/g,     valueOf: function(){      return this.r.exec(123)[0]    }  }    if (a == 1 && a == 2 && a == 3) {      console.log("!")  }

It works because of custom valueOf method that is called when Object compared with primitive (such as Number). Main trick is that a.valueOf returns new value every time because it's calling exec on regular expression with g flag, which causing updating lastIndex of that regular expression every time match is found. So first time this.r.lastIndex == 0, it matches 1 and updates lastIndex: this.r.lastIndex == 1, so next time regex will match 2 and so on.

Answers 7

It can be accomplished using the following in the global scope. For nodejs use global instead of window in the code below.

var val = 0;  Object.defineProperty(window, 'a', {    get: function() {      return ++val;    }  });  if (a == 1 && a == 2 && a == 3) {    console.log('yay');  }

This answer abuses the implicit variables provided by the global scope in the execution context by defining a getter to retrieve the variable.

Answers 8

This is also possible using a series of self-overwriting getters:

(This is similar to jontro's solution, but doesn't require a counter variable.)

(() => {      "use strict";      Object.defineProperty(this, "a", {          "get": () => {              Object.defineProperty(this, "a", {                  "get": () => {                      Object.defineProperty(this, "a", {                          "get": () => {                              return 3;                          }                      });                      return 2;                  },                  configurable: true              });              return 1;          },          configurable: true      });      if (a == 1 && a == 2 && a == 3) {          document.body.append("Yes, it’s possible.");      }  })();

Answers 9

This is possible in case of variable a being accessed by, say 2 web workers through a SharedArrayBuffer as well as some main script. The possibility is low, but it is possible that when the code is compiled to machine code, the web workers update the variable a just in time so the conditions a==1, a==2 and a==3 are satisfied.

This can be an example of race condition in multi-threaded environment provided by web workers and SharedArrayBuffer in JavaScript.

Here is the basic implementation of above:

main.js

// Main Thread  const worker = new Worker('worker.js') const modifiers = [new Worker('modifier.js'), new Worker('modifier.js')] // Let's use 2 workers const sab = new SharedArrayBuffer(1)  modifiers.forEach(m => m.postMessage(sab)) worker.postMessage(sab) 

worker.js

let array  Object.defineProperty(self, 'a', {   get() {     return array[0]   } });  addEventListener('message', ({data}) => {     array = new Uint8Array(data)     let count = 0     do {         var res = a == 1 && a == 2 && a == 3         ++count     } while(res == false) // just for clarity. !res is fine     console.log(`It happened after ${count} iterations`)     console.log('You should\'ve never seen this') }) 

modifier.js

addEventListener('message' , ({data}) => {     setInterval( () => {         new Uint8Array(data)[0] = Math.floor(Math.random()*3) + 1     }) }) 

On my MacBook Air, it happens after around 10 billion iterations on the first attempt:

enter image description here

Second attempt:

enter image description here

As I said, the chances will be low, but given enough time, it'll hit the condition.

Tip: If it takes too long on your system. Try only a == 1 && a == 2 and change Math.random()*3 to Math.random()*2. Adding more and more to list drops the chance of hitting.

Answers 10

I don't see this answer already posted, so I'll throw this one into the mix too. This is similar to Jeff's answer with the half-width Hangul space.

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

You might notice a slight discrepancy with the second one, but the first and third are identical to the naked eye. All 3 are distinct characters:

a - Latin lower case A
- Full Width Latin lower case A
а - Cyrillic lower case A

The generic term for this is "homoglyphs": different unicode characters that look the same. Typically hard to get three that are utterly indistinguishable, but in some cases you can get lucky. A, Α, А, and Ꭺ would work better (Latin-A, Greek Alpha, Cyrillic-A, and Cherokee-A respectively; unfortunately the Greek and Cherokee lower-case letters are too different from the Latin a: α,, and so doesn't help with the above snippet).

There's an entire class of Homoglyph Attacks out there, most commonly in fake domain names (eg. wikipediа.org (Cyrillic) vs wikipedia.org (Latin)), but it can show up in code as well; typically referred to as being underhanded (as mentioned in a comment, [underhanded] questions are now off-topic on PPCG, but used to be a type of challenge where these sorts of things would show up). I used this website to find the homoglyphs used for this answer.

Answers 11

Alternatively, you could use a class for it and an instance for the check.

function A() {      var value = 0;      this.valueOf = function () { return ++value; };  }    var a = new A;    if (a == 1 && a == 2 && a == 3) {      console.log('bingo!');  }

Answers 12

Javascript

a == a +1

In Javascript, there are no integers but only Numbers, which are implemented as double precision floating point number.

It means that if a Number a is large enough, it can be considered equal to 3 consecutive integers:

a = 100000000000000000  if (a == a+1 && a == a+2 && a == a+3){    console.log("Precision loss!");  }

True, it's not exactly what the interviewer asked (it doesn't work with a=0), but it doesn't involve any trick with hidden functions or operator overloading.

Other languages

For reference, there are a==1 && a==2 && a==3 solutions in Ruby and Python. With a slight modification, it's also possible in Java.

Ruby

With a custom ==:

class A   def ==(o)     true   end end  a = A.new  if a == 1 && a == 2 && a == 3   puts "Don't do this!" end 

or an increasing a:

def a   @a ||= 0   @a += 1 end  if a == 1 && a == 2 && a == 3   puts "Don't do this!" end 

Python

class A:     def __eq__(self, who_cares):         return True a = A()  if a == 1 and a == 2 and a == 3:     print("Don't do that!") 

Java

It's possible to modify Java Integer cache:

package stackoverflow;  import java.lang.reflect.Field;  public class IntegerMess {     public static void main(String[] args) throws Exception {         Field valueField = Integer.class.getDeclaredField("value");         valueField.setAccessible(true);         valueField.setInt(1, valueField.getInt(42));         valueField.setInt(2, valueField.getInt(42));         valueField.setInt(3, valueField.getInt(42));         valueField.setAccessible(false);          Integer a = 42;          if (a.equals(1) && a.equals(2) && a.equals(3)) {             System.out.println("Bad idea.");         }     } } 

Answers 13

Rule number one of interviews; never say impossible.

No need for hidden character trickery.

window.__defineGetter__( 'a', function(){      if( typeof i !== 'number' ){          // define i in the global namespace so that it's not lost after this function runs          i = 0;      }      return ++i;  });    if( a == 1 && a == 2 && a == 3 ){      alert( 'Oh dear, what have we done?' );  }

Answers 14

This is an inverted version of @Jeff's answer* where a hidden character (U+115F, U+1160 or U+3164) is used to create variables that look like 1, 2 and 3.

var  a = 1;  var ᅠ1 = a;  var ᅠ2 = a;  var ᅠ3 = a;  console.log( a ==ᅠ1 && a ==ᅠ2 && a ==ᅠ3 );

* That answer can be simplified by using zero width non-joiner (U+200C) and zero width joiner (U+200D). Both of these characters are allowed inside identifiers but not at the beginning:

var a = 1;  var a‌ = 2;  var a‍ = 3;  console.log(a == 1 && a‌ == 2 && a‍ == 3);    /****  var a = 1;  var a\u200c = 2;  var a\u200d = 3;  console.log(a == 1 && a\u200c == 2 && a\u200d == 3);  ****/

Other tricks are possible using the same idea e.g. by using Unicode variation selectors to create variables that look exactly alike (a︀ = 1; a︁ = 2; a︀ == 1 && a︁ == 2; // true).

Answers 15

Honestly though, whether there is a way for it to evaluate to true or not (and as others have shown, there are multiple ways), the answer I'd be looking for, speaking as someone who has conducted hundreds of interviews, would be something along the lines of:

"Well, maybe yes under some weird set of circumstances that aren't immediately obvious to me... but if I encountered this in real code then I would use common debugging techniques to figure out how and why it was doing what it was doing and then immediately refactor the code to avoid that situation... but more importantly: I would absolutely NEVER write that code in the first place because that is the very definition of convoluted code, and I strive to never write convoluted code".

I guess some interviewers would take offense to having what is obviously meant to be a very tricky question called out, but I don't mind developers who have an opinion, especially when they can back it up with reasoned thought and can dovetail my question into a meaningful statement about themselves.

Answers 16

Javascript

Yes, it is possible! 😎

if‌=()=>!0;  var a = 9;    if‌(a==1 && a== 2 && a==3)  {      document.write("<h1>Yes, it is possible!😎</h1>")  }

The above code is a short version (thanks to @Forivin for its note in comments) and the following code is original:

var a = 9;    if‌(a==1 && a== 2 && a==3)  {      //console.log("Yes, it is possible!😎")      document.write("<h1>Yes, it is possible!😎</h1>")  }    //--------------------------------------------    function if‌(){return true;}

If you just see top side of my code and run it you say WOW, how?

So I think it is enough to say Yes, it is possible to someone that said to you: Nothing is impossible

Trick: I used a hidden character after if to make a function that its name is similar to if. In JavaScript we can not override keywords so I forced to use this way. It is a fake if but works for you in this case!


C#:

Also I wrote a C# version (with increase property value technic): Live Demo

static int _a; public static int a {get{ ++_a; return _a;}}  public static void Main() {     if(a==1 && a==2 && a==3)     {         Console.WriteLine("Yes, it is possible!😎");     } } 

Answers 17

Here's another variation, using an array to pop off whatever values you want.

const a = {    n: [3,2,1],    toString: function () {      return a.n.pop();    }  }    if(a == 1 && a == 2 && a == 3) {    console.log('Yes');  }

Answers 18

If you ever get such an interview question (or notice some equally unexpected behavior in your code) think about what kind of things could possibly cause a behavior that looks impossible at first glance:

  1. Encoding: In this case the variable you are looking at is not the one you think it is. This can happen if you intentionally mess around with Unicode using homoglyphs or space characters to make the name of a variable look like another one, but encoding issues can also be introduced accidentally, e.g. when copying & pasting code from the Web that contains unexpected Unicode code points (e.g. because a content management system did some "auto-formatting" such as replacing fl with Unicode 'LATIN SMALL LIGATURE FL' (U+FB02)).

  2. Race conditions: A race-condition might occur, i.e. a situation where code is not executing in the sequence expected by the developer. Race conditions often happen in multi-threaded code, but multiple threads are not a requirement for race conditions to be possible – Asynchronicity is sufficient. Note that therefore JavaScript is also not free from race conditions just because it is single-threaded (unless you are using web workers1). See here for a simple single-threaded – but async – example. In the context of an if-statement the race condition however would be rather hard to hit in JavaScript without web workers.

  3. Side-effects: A side-effect of the equality comparison operation (which doesn't have to be as obvious as in the examples here, often side-effects are very subtle).

These kind of issues can appear in many programming languages, not only JavaScript, so we aren't seeing one of the classical JavaScript WTFs here2.

Of course, the interview question and the samples here all look very contrived. But they are a good reminder that:

  • Side-effects can get really nasty and that a well-designed program should be free from unwanted side-effects.
  • Multi-threading and mutable state can be problematic.
  • Not doing character encoding and string processing right can lead to nasty bugs.

1 @mehulmpt has a great proof-of-concept using web workers.

2 For example, you can find an example in a totally different programming language (C#) exhibiting a side-effect (an obvious one) here.

Answers 19

Okay, another hack with generators:

const value = function* () {    let i = 0;    while(true) yield ++i;  }();    Object.defineProperty(this, 'a', {    get() {      return value.next().value;    }  });    if (a === 1 && a === 2 && a === 3) {    console.log('yo!');  }

Answers 20

Actually the answer to the first part of the question is "Yes" in every programming language. For example, this is in the case of C/C++:

#define a   (b++) int b = 1; if (a ==1 && a== 2 && a==3) {     std::cout << "Yes, it's possible!" << std::endl; } else {     std::cout << "it's impossible!" << std::endl; } 

Answers 21

Same, but different, but still same (can be "tested" multiple times):

const a = { valueOf: () => this.n = (this.n || 0) % 3 + 1}        if(a == 1 && a == 2 && a == 3) {    console.log('Hello World!');  }    if(a == 1 && a == 2 && a == 3) {    console.log('Hello World!');  }

My idea started from how Number object type equation works.

Answers 22

Since I haven't seen any answers using Proxies yet:

var a = new Proxy({ i: 0 }, {     get: (target, name) => name === Symbol.toPrimitive ? () => ++target.i : target[name], }); console.log(a == 1 && a == 2 && a == 3); 

Proxies basically pretend to be a target object (the first parameter) but intercept operations on the target object (in this case the "get property" operation) so that there is an opportunity to do something other than the default object behavior. In this case the "get property" action is called on a when == coerces its type in order to compare it to each number. So what's happening here is:

  1. We create a target object, { i: 0 }, where the i property is our counter
  2. We create a Proxy for the target object and assign it to a
  3. For each a == comparison, a's type is coerced to a primitive value
  4. This type coercion results in calling a[Symbol.toPrimitive]() internally
  5. The Proxy intercepts getting the a[Symbol.toPrimitive] function using the "get handler"
  6. The Proxy's "get handler" checks that the property being gotten is Symbol.toPrimitive, in which case it increments and then returns the counter from the target object: ++target.i. If a different property is being retrieved, we just fall back to returning the default property value, target[name]

So:

var a = ...; // a.valueOf == target.i == 0 a == 1 && // a == ++target.i == 1 a == 2 && // a == ++target.i == 2 a == 3    // a == ++target.i == 3 

As with most of the other answers, this only works with a loose equality check (==) because strict equality checks (===) do not do type coercion that the Proxy can intercept.

Answers 23

I think this is the minimal code to implement it:

i=0,a={valueOf:()=>++i}    if (a == 1 && a == 2 && a == 3) {    console.log('Mind === Blown');  }

Creating a dummy object with a custom valueOf that increments a global variable i on each call. 23 characters!

Answers 24

An ES6 answer that makes use of Symbols:

const a = {value: 1}; a[Symbol.toPrimitive] = function() { return this.value++ }; console.log((a == 1 && a == 2 && a == 3)); 

Due to == usage, Javascript is supposed to coerce a into something close to the second operand (1, 2, 3 in this case). But before Javascript tries to figure coercing on its own, it tries to call Symbol.toPrimitive. If you provide Symbol.toPrimitive JS would use the value your function returns. If not, JS would call valueOf.

Answers 25

This one uses the defineProperty with a nice side-effect causing global variable!

var _a = 1    Object.defineProperty(this, "a", {    "get": () => {      return _a++;    },    configurable: true  });    console.log(a)  console.log(a)  console.log(a)

Answers 26

Even without confusing naming, overloading, or random variables, a == 1 && a == 2 && a == 3 can return true in multi-threaded environments as the value of a may change between each comparison as long as it is not thread-safe.

Answers 27

The main reason why this could be equals is == operators, with === won't work.

const a = {     i: 0;     valueOf: function() {        return this.i++;     }  }  if(a == 1 && a == 2 && a == 3) // true 

Because the methods valueOf and toString will be called when the == operators are used.

if(a === 1 && a === 2 && a === 3) // false 

The valueOf and toString methods are not called.

Answers 28

Another solution is to override the prototype.toString function for a Set structure from Javascript.

Suppose we have a Set called a with three values.

var a = new Set([1,2,3]); 

When we compare one Set with a primitive type it's triggered toString function from Set class because we need to coerce the left member.

Set.prototype.toString=function(){    let first = [...a][0];    this.delete(first);    return first; } 

var a=new Set([1,2,3]);  Set.prototype.toString = function(){     let first = [...a][0];     this.delete(first);     return first;  }  console.log(a==1 && a==2 && a==3);

In fact, since we compare two different data types , we can do that with a lot of data structures from javascript and we have advantage that javascript is weakly-typed language.

We just need to override the toString property of given data type, because when we use == it invokes toString function.

Answers 29

If you use webpack, you can use a lovely config like that:

const { DefinePlugin } = require('webpack') const config = {     plugins: [         new DefinePlugin({ 'a': '(window.a = ++window.a || 1)' })     ] } 

Answers 30

While there are already a lot of good answers to the question, but my response to the interviewer will be:

Yes, there may special cases that will make this expression evaluated to true but I will try to avoid coding like this. As it is not good coding practice and will create confusions to the future maintainers of the code.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment