OneBite.Dev - Coding blog in a bite size

concatenate strings in javascript

Code snippet for how to how to concatenate strings in javascript with sample and detail explanation

In this article, we are going to discuss an essential part of scripting - concatenating strings in JavaScript. Working with strings is a common task in JavaScript and in this guide, we will be detailing the process of joining strings together, also known as string concatenation.

Code Snippet for Concatenating Strings

In JavaScript, there are several methods to concatenate strings, but we will focus on the ”+” operator method and the concat() method.

Here’s a simple code snippet using the ”+” operator:

var str1 = "Hello";
var str2 = "World";
var res = str1 + " " + str2;
console.log(res); // Outputs: Hello World

For the concat() method, here is a simple code snippet:

var str1 = "Hello";
var str2 = "World";
var res = str1.concat(" ", str2);
console.log(res); // Outputs: Hello World

Code Explanation for Concatenating Strings

In our examples above, we had two strings str1 and str2 which we needed to concatenate or join.

In the first example, we used the ”+” operator to join two or more strings. The ”+” operator can be used directly to concat two strings. In this instance, we also included an extra space (” ”) in between to separate the two strings.

var res = str1 + " " + str2;

The above line of code will take the string in str1, add a space, and then add the string in str2. The concatenated string is then stored in the variable res.

In the second example, we used the concat() method. The concat() function in JavaScript is used to join two or more strings and return a new string.

var res = str1.concat(" ", str2);

The concat() method does not change the existing strings, but returns a new string containing the text of the joined strings.

In both examples, we used the console.log() function to print out the result - in this case, the phrase ‘Hello World’. This allows us to see the final concatenated string.

Those are two of the simple ways to concatenate strings in JavaScript. Depending on the specifics of your code, one method may be more suitable than the other. However, both these techniques will lead you to the same result. Happy coding!

javascript