The Dangers of the ‘+’ Operator in JavaScript

How simple addition can misfire and break JavaScript applications in ways you might not expect

Chris Geelhoed
Jan 13 · 4 min read
Photo by Kevin Jarrett on Unsplash

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:

  1. Adding numbers
  2. 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 users can see how much they have spent as they shop.

The subtotal is calculated by taking the sum of all of the products in the user’s cart. Product data is fetched from a REST API in JSON format. The products in the user’s cart are represented with an array of object literals. It could look like this, for example:

[
{
"id": 23173128,
"title": "Nutella Hazelnut Spread",
"price": 8
},
{
"id": 89123012,
"title": "Oreo Chocolate Sandwich",
"price": 5
}
]

And you might calculate the sum of the products in the cart by using the + operator in combination with the reduce array method:

const subtotal = productsInCart
.reduce((total, product) => total + product.price, 0)

This works well at the moment, but what happens if the backend API changes and the price is accidentally converted from a number to a string?

{
{
"id": 23173128,
"title": "Nutella Hazelnut Spread",
"price": "8" // Price is now a string!
},
{
"id": 89123012,
"title": "Oreo Chocolate Sandwich Cookies",
"price": "5"
}
}

The code will still run, but the result will now be different. 8 + 5 results in 13, but '8' + '5' results in '85'! No error is thrown, so the bug could slip through to production undetected.

This is dangerous!


How To Avoid This Problem

If you want to add numbers that you don’t have absolute control over (like from an API or user input, for example) then it’s a good idea to explicitly force your values to be numbers using parseInt, parseFloat, Number, or similar.

console.log(parseInt('2') + parseInt('2')) // This outputs 4

The bug introduced in the ecommerce example above could be avoided by passing the price of each of the cart’s items through the parseFloat function:

const subtotal = productsInCart
.reduce((total, product) => total + parseFloat(product.price), 0)

On the other hand, if you want to form a string from values that could include numbers, then you should explicitly force those values to be strings:

const prefix = 777
const suffix = 888
const result = prefix.toString() + suffix.toString()
console.log(result) // Outputs '777888'

Even better, don’t use the + operator for formatting strings. Use ES6 template literals instead:

const prefix = 777
const suffix = 888
const result = `${prefix}${suffix}`
console.log(result) // Outputs '777888'

Summary

The + operator is used to perform both addition and string concatenation in JavaScript. If you aren’t careful, this dual-purpose functionality can lead to dangerous bugs where concatenation occurs when addition is intended or vice versa.

The best way to handle this potential issue is to proactively cast unknown data to its intended type. Values can be cast to numbers by using parseInt, parseFloat, or Number. Values can be cast to strings by using the toString method or by using template literals.

Better Programming

Advice for programmers.

Chris Geelhoed

Written by

Software developer and teacher

Better Programming

Advice for programmers.

More From Medium

More from Better Programming

More from Better Programming

More from Better Programming

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade