1

I recently implemented a very simple method to extend the base JavaScript Number Class and tried to call it directly on an entered number in the browser console.

123.myMethod();

But it is not working as expected, it only says: "Invalid or unexpected token"

I was unsure, if I can call Number Methods directly on entered numbers, so I tried standard methods like .toFixed():

123.toFixed(1);

But this also isn't working.

Only if I write a float, I can call Number methods:

123.0.toFixed(1);

It also works, if I put the Integer inside brackets:

(123).toFixed(1);

So my question is: Why are Integers not implicitly casted to Number and why can't I use Number methods on them?

Alex K
  • 13
  • 2

1 Answers1

3

The . tells the JavaScript interpreter to be a decimal point, so it is expecting more numbers. In JavaScript there is only floats, no integers.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • Hmmm... I think I'll go with (123).myMethod() then as explicitly casting like parseInt(123).myMethod() looks a bit ugly ;-) – Alex K Oct 18 '18 at 11:49
  • `parseInt(123)` is not "explicitly casting" anything. First of all, it's *parsing*. It will turn whatever you give it into a *string* and then it would read it character by character to extract the number value. What you get is *usually* the exact same number but really large numbers can be mangled. Also, you still get a primitive out of it, you don't get a Number object. To do that you'd need to do `new Number(123)` but beware that `new Number(123) !== new Number(123)` because they are *different objects*. `primitiveNumber.myMethod()` also works as you get the implicit conversion into object. – VLAZ Oct 18 '18 at 12:01