4

I've been asked in a JavaScript interview

If x!=x is TRUE, what is the possible type of x?

The interviewer told me there is only one possible type for x that gets this result.

SuperBiasedMan
  • 9,814
  • 10
  • 45
  • 73
sundeepg
  • 432
  • 2
  • 8
  • 18
  • 5
    `Object.defineProperty(window, 'x', {get: function () {return Math.random();}})` – Paul S. Sep 08 '15 at 11:49
  • Next interview question: Perform a code review on the following https://www.destroyallsoftware.com/talks/wat – Lix Sep 08 '15 at 11:49
  • 1
    @Cerbrus as the question mentions _types_ lets fill in a couple more, _String_, `Object.defineProperty(window, 'x', {get: function () {return String.fromCharCode(Math.random() * 0xFFFF | 0);}})`, _Bool_, `Object.defineProperty(window, 'x', {get: function () {return !(Math.random() * 2 | 0);}})`, _Function_ `Object.defineProperty(window, 'x', {get: function () {return function () {};}})` – Paul S. Sep 08 '15 at 12:03

2 Answers2

14

The value is NaN, which is of type Number.

From the spec for comparing equality:

If x is NaN, return false.

NaN is never equal to anything, including itself.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
11

If x!=x is true, what is the possible type of x?

Assuming that x is meant to be a variable, the answer to this question is:

"number"

The only value that satisfies this requirement is NaN, which never equals itself.

As you can see, the type of NaN is "number":
typeof NaN === "number".


If x is merely a placeholder for anything, functions and object or array literals would work, too:

(function(){}) != (function(){})
({}) != ({})
[] != []

If x can be a getter, then there's all sorts of crazy options:

// Type == "string"
Object.defineProperty(window, 'x', {
    get: function() { return String.fromCharCode(Math.random() * 0xFFFF | 0); }
});

// Type == "boolean"
Object.defineProperty(window, 'x', {
    get: function() { return !(Math.random() * 2 | 0); }
});

// Type == "function"
Object.defineProperty(window, 'x', {
    get: function() { return function() {}; }
});

// Type == "object"
Object.defineProperty(window, 'x', {
    get: function() { return ({}); }
});

// Type == "object"
Object.defineProperty(window, 'x', {
    get: function() { return []; }
});

Using with:

var o = {};
Object.defineProperty(o, 'x', {
  get: function() { return []; } // any of the above types
});

with(o){
  alert(x != x);
}

(Thanks to @Paul S.)

Community
  • 1
  • 1
Cerbrus
  • 70,800
  • 18
  • 132
  • 147