Member-only story
The Dangers of the ‘+’ Operator in JavaScript
How simple addition can misfire and break JavaScript applications in ways you might not expect
Like most programming languages, JavaScript has a +
operator that can be used to perform addition. Unlike other programming languages, however, the operator also serves a second purpose: string formatting.
This piece explores how the +
operator works, and how it can misfire and cause bugs if you aren’t careful. It also shows how these issues can be avoided in the first place.
The Basics
As mentioned, the +
operator has two purposes in JavaScript:
- Adding numbers
- Concatenating strings
The +
operator’s first purpose is to add numbers together. Here’s an example:
const price = 20
const shipping = 3
const tax = 3
const total = price + shipping + tax
console.log(total) // Outputs 26
The operator’s other purpose is to concatenate (join together) strings. It can be used like this:
const firstName = 'Marty'
const lastName = 'McFly'
const fullName = firstName + ' ' + lastName
console.log(fullName) // Outputs 'Marty McFly'
This seems at least workable so far, but what happens when you use numbers in their string form?
console.log('2' + '2') // This outputs '22'
The behavior of the operator depends on the type of data it is given. If it receives two numbers then it will perform addition. If you give it one or more strings, however, the behavior changes to string concatenation.
console.log(2 + '2') // This also outputs '22'!
The ambiguous nature of the +
operator can cause big problems in JavaScript applications. Let’s look at how.
A Real-World Example
The example above shows this problem in its most basic form. In the real world, however, the problem often gets hidden in complexity. Here’s a more realistic situation:
Your company maintains an ecommerce website. You are assigned the task of adding a subtotal indicator to the header of the website so that…