Sitemap
Better Programming

Advice for programmers.

The Dangers of the ‘+’ Operator in JavaScript

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

4 min readJan 13, 2020

--

Press enter or click to view image in full size
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'

--

--

Responses (3)