Append two strings together in javascript (with edge cases)

Chris Achard
InstructorChris Achard
Share this video with your friends

Social Share Links

Send Tweet

There are two methods to append strings together in javascript, but there are edge cases that you have to watch out with each of them.

First, you can use the + operator to add strings together:

"first" + " " + "second"

which works, but watch out! If one of your variables is a non-string value, then it will try to convert that to a string before adding it to the other string.

The other method is to use the concat method:

"first".concat(" ", "second")

but concat has a big problem because now if the first value is a non-string value (like null or undefined), then it will cause a runtime error, since the concat method is undefined on those values.

For that reason, most people use the + operator to add two strings together in javascript.

Chris Achard: [0:00] We're going to call one, a, and we're going to call the other one, b. Then we want to concatenate these two together. We're going to log the output of our values here, and we're just going to start with a + b. Just like math, except it concatenates the two strings together.

[0:16] We can add other strings in here, too. We can have a blank in there to get a space. The cool thing about this plus method is that, if one of these strings is not a string but say a number, then it will convert that to a string when adding it together.

[0:33] You have to be careful though, because if this is something like null, then it will try to convert that to a string and just call a null. Same thing for undefined, and the same thing for arrays and objects.

[0:45] If you put an object here or try to convert that to a string, and it just says [object Object] . If you have an array, it converts that to a string with nothing in it. Now, if you have multiple elements in the array, it will helpfully put those with commas, but you have to watch these edge cases when you're using plus to add strings together.

[1:02] There is another method. If we switch this back to "first", we can say a.concat, and then we can put b in there to get first and second. We can even put a space, and then we have two arguments to concat or more than two.

[1:17] Here, we have first and second. This seems like it might be a better idea, but you have to really watch this one. If we switch one of these first to a 1, for example, then we get an error, actually, because the number 1 doesn't have a concat method.

[1:32] Some people instead, switch this to a empty string and then they can say a,. Now, this works just like before, even with nulls. With null that will convert it to the string null. This seems awfully confusing. Most people stick with the plus method of concatenation, but you just have to watch out for the edge cases of non-string values.