Pawan Pawan - 9 months ago 45
Javascript Question

number toString() method returns different values for number and variable

If I run

var num = 23;
var n = num.toString();

it logs
as expected but if I apply the
directly to a number like,

var n = 15.toString();

it throws an error:
Uncaught SyntaxError: Invalid or unexpected token

I noticed it also works fine for decimal values in the num variables (like .3, .99, 2.12, 99.1) etc. Could some one please help me understand the difference and how this function works

Answer Source

JavaScript parsing is working as intended. You have declared the following:


We see this as an Integer with a function being called on it.

The parser doesn't. The parser sees an attempt to declare a floating-point literal. The parser uses this:


It assumes that you are declaring a Floating-Point Literal because it is:

  • not a variable, as it doesn't start with a letter or acceptable character
  • is a numeric literal, as it starts with a numeric character
  • is a floating point number, as it has a decimal point in it.

If you really, for all intents and purposes, want to call 23.toString(), the course of action is to isolate the literal like so:

(23).toString(); //interprets 23 as literal


23..toString(); //interprets 23. as literal

That being said, JavaScript is flexible enough to know you want to use 23 as a String in most cases. This compiles fine.

var foo = "The answer is " + 42;  

So does this.

var bar = "39" - 0 + 3; //42

This doesn't.

var baz = "39" + 3; //393!!!