Double and Single Quotes

In chapter 1, Converting Between Strings and Numbers: Are the quotes significant? Why aren't they the same?

const answer = '5' * 1;

typeof answer

<< "number"

const answer = + '5';

typeof answer

<< 'number'

Link to content: JavaScript: Novice to Ninja, 2nd Edition - Section 2

1 Like

In the first one:

const answer = ‘5’ * 1;

The * 1 is coercing the string ‘5’ into a number, so it can perform the multiplication. Since a string can’t be multiplied, JavaScript converts it to a number first.

In the second one:

const answer = + ‘5’;

The + symbol here is actually the unary plus operator. This explicitly converts the ‘5’ string into a number type.

So in both cases, the end result is that ‘5’ gets converted into the number 5.

But the key difference is that the first example relies on implicit coercion by using * 1. The second uses explicit conversion with the + operator.

So while the end result is the same (a number 5), the * 1 and + operators work differently under the hood to convert between the string and number types.

The quotes indicate it starts as a string, while leaving them off would indicate a number to begin with. The quotes are significant in signaling the starting data type before the conversion.

Hope this helps explain why those two approaches are not exactly the same even though the end result is! Let me know if any other questions come up.

1 Like

Some people consider implicit conversions such as that to be a nice convenience. When implicit conversions cause confusion it might be considered a disadvantage of the language.

1 Like

Hah, I’d say it’s a typo. I’ll mention it on GitHub.

1 Like