Math with strings?

This article introduces how JavaScript performs string concatenation with strings, and uses NaN to signify when a math operation is attempted that isn't possible

As you’ve seen, string concatenation in JavaScript is possible using the + operator. In this article, we aim to clear up some misconceptions you might have about doing math-like operations with strings.

This example shows the use of the + operator to connect multiple strings.

let firstName = "Freddy" let lastName = "Williams" let fullName = firstName + " " + lastName

However, it is important to note that JavaScript isn’t actually performing addition, or any math at all here. When JavaScript comes across the + operator without numbers on either side, it instead concatenates one string onto the end of the other.

Other types of math operators cannot be used with strings in JavaScript. If you attempt to do this, the value returned will be NaN, which is short for Not a Number. NaN is the value given when arithmetic operators are used in a way that does not actually yield a number

let fullName = "Riley Davidson" let lastName = "Davidson" let firstName = fullName - lastName console.log(firstName) // this will log NaN, because only addition is supported for strings

If you’re coming to JavaScript from a different language, such as Python, this might be behavior that you aren’t used to. For example, Python allows multiplication to perform multiple string concatenations. This is not supported in JavaScript, and will instead evaluate to NaN.

# Danger, you are in the PYTHON ZONE food = "pizza" moar_food = "food * 3 print(moar_food) # this prints "foodfoodfood" but doesn't work in JavaScript

JavaScript will even perform string concatenation on values that aren’t strings or numbers by converting them into strings and then concatenating the strings together.

console.log([11, 22, "dog"] + [33, "cat"]) // In this example, JavaScript will convert both arrays to strings and then concatenate them together, yielding one big string with commas between what used to be different elements in each array

Test your understanding by answering the question below.