Given x!=x in JavaScript. What is the type of 'x'? [duplicate]

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.

Answers:

Answer

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

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.