The typical issue brought up for string concatenation revolves around a few issues:
- the
+
symbol being overloaded
- simple mistakes
- programmers being lazy
#1
The first and foremost issue with using +
for string concatenation and addition is that you're using +
for string concatenation and addition.
if you have variables a
and b
, and you set c = a + b
, there is an ambiguity dependent on the types of a
and b
. This ambiguity forces you to take extra steps to mitigate the issue:
String Concat:
c = '' + a + b;
Addition:
c = parseFloat(a) + parseFloat(b);
This brings me to my second point
#2
It's very easy to accidentally cast a variable to a string without realizing it. It's also easy to forget that your input is coming in as a string:
a = prompt('Pick a number');
b = prompt('Pick a second number');
alert( a + b );
Will produce unintuitive results because prompt returns the string value of the input.
#3
Needing to type parseFloat
or Number()
every time I want to do addition is tedious and annoying. I think of myself as smart enough to remember not to mess up my dynamic types, but that doesn't mean I've never messed up my dynamic types. The truth of the matter is that I'm too lazy to type out parseFloat
or Number()
every time I do addition, because I do a lot of addition.
Solution?
Not all languages use +
for string concatenation. PHP uses .
to concatenate strings, which helps distinguish between when you want to add numbers and when you want to join strings.
Any symbol could be used to concatenate strings, but most are already used, and it's best to avoid duplication. If I had my way, I'd probably use _
to join strings, and disallow the _
in variable names.
bad
. Who isEveryone
?