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.
There are 3 JavaScript methods that can be used to convert variables to numbers: The Number() method. The parseInt() method. The parseFloat() method.
The Number() method converts a value to a number. If the value cannot be converted, NaN is returned.
In JavaScript, numbers are primitive data types. For example, const a = 3; const b = 3.13; Unlike in some other programming languages, you don't have to specifically declare for integer or floating values using int, float, etc.
JavaScript has several special number values: Two error values, NaN and Infinity . Two values for zero, +0 and -0 . JavaScript has two zeros, a positive zero and a negative zero, because the sign and the magnitude of a number are stored separately.
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.
Most of the answers already stated that a dot after a numeric literal is considered part of this number as a fraction separator. But if you still want to use the dot as an operator then the quick and easy fix would be leaving an empty space between the number and the space.
2 .isIn(1,2,3,4,5) // <- notice the space between 2 and .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With