Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange syntax of Number methods in JavaScript

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.

like image 252
Andreas Grech Avatar asked Dec 07 '09 16:12

Andreas Grech


People also ask

What are the methods of JavaScript numbers?

There are 3 JavaScript methods that can be used to convert variables to numbers: The Number() method. The parseInt() method. The parseFloat() method.

What is number function JavaScript?

The Number() method converts a value to a number. If the value cannot be converted, NaN is returned.

What are number in JavaScript with example?

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.

What are special numbers in JavaScript?

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.


2 Answers

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.

like image 187
Josh Stodola Avatar answered Oct 11 '22 18:10

Josh Stodola


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 .
like image 39
Andris Avatar answered Oct 11 '22 19:10

Andris