String Concatenation Using + in JavaScript

Alec Scully
2 min readJun 13, 2021

Recently I came across a JavaScript quiz that had all sorts of questions ranging from a beginner difficulty, to more advanced topics. One question revolved around adding multiple different data types, including an unassigned variable. I typed out what I can remember from this particular question below:

There is an unassigned variable, a string, and an integer. Using those three variables were then added, and I was asked the result of said addition. The answers are below:

To break it down, the JavaScript + operator is used in both number addition as well as string concatenation. When it sees a string being concatenated with anything, it will automatically convert that other thing to a string. You can that b1 is adding an undefined variable with a string, so it concatenates to “undefined3”. Second, b2 is trying to add a number with an undefined variable, so it evaluates to NaN (Not-a-Number). Lastly, b3 is another string concatenation instead of addition. You may think it would evaluate to 6, but it will actually concatenate to the string “33”.

Now we will go one step further and do another round of concatenation to further solidify this topic. Below you will see a new variable being created, and set to one b variable being added with one original a variable.

The output we see matches our first case. Each of these outputs is converted to a string upon being concatenated. The only new case is c2. If we check the type of b2 (NaN) we will get an error due to NaN being a special variable. After this second round, if we check the type again, we see that “NaN3” is now a string.

I hope you learned a little bit over this simple question, just like I did!

--

--