String concatenation operator considered harmful

Cory
2 min readApr 16, 2021

It’s been a minute since I’ve last seen a “considered harmful” story. I’d say it’s about time for a new one.

To be honest though, I do consider the string concatenation operator (+) in JavaScript problematic. For one thing, it’s overloaded with the numerical add operator (also +). In strongly typed languages this is less of a problem, but I don’t know that it helps with human readability. In a dynamically typed language like JavaScript though, it can be down right dangerous.

The problem

What does this even mean?

2 + 'Hello'

I know what it does, but what does it mean, logically? It doesn’t make any sense. Image saying something like “Pickle more hours till noon” or “If Sally had four apples and gave swimming to Patrick, how many apples does Sally have?” This is nonsense, but it makes about as much sense as 2 + 'Hello' . Yet this is perfectly valid JavaScript.

No doubt this is a contrived example, but what about this?

const finalVal = valA + valB

Uh oh! But still, I’m sure it wouldn’t take long to look at the file and figure out what valA and valB are meant to be. It’s not ideal, but maybe we wouldn’t go so far as to say it’s harmful… unless…

const combine = (a, b) => a + b

Hmmm, could be add. Could also be concat. What are we trying to accomplish here? Again. Contrived, but you can see the principle of the problem.

I think it’s fair to say that + is much more associated with addition than with concatenation, so let’s leave + to the maths.

The solution

Ok, so now we know we shouldn’t use + for string concatenation, but what should we use. Well, we could go a few different ways, but I think the most obvious — the one that makes it very clear we mean to be dealing with building up a string — is by using template literals.

const combine = (a, b) => `${a}${b}`

That’s much nicer. It obvious that we are trying to combine strings here. Sure, value coercion to strings can still happen if one of the values is not a string, but it is evident that the end result here is going to be a string. With + we could get a number or a string, depending on what values we are combining.

Let’s do our selves a favor and stop using + for string concatenation. Let’s use template literals instead.

--

--

Cory

Front End Engineer with deep technical expertise in JS, CSS, React, Frontend Architecture, and lots more. I lean functional, but I focus on maintainability.