When I enter a literal integer followed by .toString()
into Node, it enters a new scope by responding with ...
.
> 3.toString()
...
> 'foo:' + 3.toString()
...
> 'foo:' + 3.toString() + ':bar'
...
> true.toString()
'true'
Even this works!
> 10.50.toString()
'10.5'
Wrapping the literal integer in parenthesis works:
> (3).toString()
'3'
Is there a reason for this or do you think it's a bug?
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."
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