Question

When I enter a literal integer followed by .toString() into Node, it enters a new scope by responding with ....

Examples

> 3.toString()
...

> 'foo:' + 3.toString()
...

> 'foo:' + 3.toString() + ':bar'
...

Other types seem to work fine

> true.toString()
'true'

Even this works!

> 10.50.toString()
'10.5'

Workaround

Wrapping the literal integer in parenthesis works:

> (3).toString()
'3'

Is there a reason for this or do you think it's a bug?

Was it helpful?

Solution

That is because when JavaScript sees a period after an integer, it assumes the value after it will be its decimals. Because of that, simply using 5.toString() will make JavaScript find toString where it expected numbers. If you place it within parentheses, or include decimals yourself, it will work. In fact, this (although it's a bit less clear to read as a human) will work too:

5..toString()

since an empty decimal point will make JavaScript turn the integer 5 into a float 5, which would prevent it from assuming there'll be numbers after the next period. That will make JavaScript expect a method after the next period.

What you could also use though is the fact that JavaScript automatically detects the type of the things you're working with. That means you can also simply use this:

5+''

This will also work when placed mid-string:

console.log('We will need '+ 5+5 + 'pizzas.');
//"We will need 55 pizzas."
console.log('We will need '+ (5+5) +' pizzas.');
//"We will need 10 pizzas."
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top