Reputation: 4961
Suppose a variable x
has numeric value 0.5
.
"cake" + x
will return "cake0.5"
without complaining. What are the merits of explicitly writing "cake" + x.toString()
in the code in Javascript? I expect it's considered better code-style to be explicit. But I'm not very experienced with JS. Is it more performant to write the explicit conversion, rather than allow the compiler to figure it out?
When would there be a reason to omit the explicit conversion?
Upvotes: 1
Views: 77
Reputation: 4148
In your example you can either use of omit the .toString()
method.
Why to use it at all? It depends on your needs. This method allow you to covert numbers from base 2 to base 36:
const myNumber = 32;
myNumber.toString(2); // Binary - returns 100000
myNumber.toString(8); // Octal - returns 40
myNumber.toString(10); // Decimal (default) - returns 32
myNumber.toString(16); // Hexadecimal - returns 20
myNumber.toString(32); // Triacontakaidecimal - returns 10
Upvotes: 1
Reputation: 50807
The main reason to include it is to make your code more explicit. Depending on implicit conversions can make the code harder to understand for the next person who reads it -- even if that's yourself a few weeks later. If I see "cake" + x
, my first guess is that x
might be something like "pan"
or "mix"
. I wouldn't guess that it's a number.
Upvotes: 1
Reputation: 386883
Maybe it is a habit to convert both operands to the same type, which is mandatory for typed languages.
"cake" + x.toString()
is more precise than to think of using implicit coercion. The reader of the code can have a clear view what is going on.
Upvotes: 2
Reputation:
There's no real reason to use toString() rather than explicity. The speed varies but it's really insignificant (and speed is browser dependant).
Upvotes: 1
Reputation: 40
Using either method is okay. I've seen engineers write it both ways.
Performance-wise, it's such a negligible difference nobody really will criticize you for using one or the other.
So whichever you prefer, use. It's good to know, however, that both will result in the same outcome...that way when you come across either of them in someone's code, you'll know what it means.
Upvotes: 1