Take a look at the following code:
Number.prototype.isIn = function () {
for (var i = 0, j = arguments.length; i < j; ++i) {
if (parseInt(this, 10) === arguments[i]) {
return true;
}
}
return false;
};
var x = 2;
console.log(x.isIn(1,2,3,4,5)); // <= 'true'
console.log(2.isIn(1,2,3,4,5)); // <= Error: 'missing ) after argument list'
Why is it that when it’s a variable, the code works correctly yet when it is a number literal, it fails ?
And also, strangely enough, why does the following line work?
console.log((2).isIn(1,2,3,4,5)); // <= 'true'
In the above line, I basically enclosed the literal in parenthesis.
It’s a syntax error because you are representing a number. Strings can work that way, but not numbers, because a period immediately following a number symbolizes a decimal value. The character after the
.is causing the error.