Skip to content

Try our new Crash Courses!

Become a member using the button below to hide this banner and gain access to our new Crash Courses.

Combining strings – JavaScript

Summary

let greeting = 'hello' + ' world';
greeting += '!';
// greeting = 'hello world!'

Details

To concatenate (or combine) strings, you can use the plus sign:

// Concatenate string literals
const newString = "Hello " + "world";
// newString now equals "Hello world"

It also works with variables that contain strings, like this:

// Concatenate strings using variables
const firstString = "Hello ";
const secondString = "world";
const firstPlusSecondString = firstString + secondString;
// firstPlusSecondString now equals "Hello world"

If you try to combine two strings that contain numbers, the strings are combined, instead of added together.

const numberString = '1' + '1';
// numberString now equals '11', not '2' or 2

If you try to add a number to a string, the number is converted into a string and the strings are combined.

const numberString = '1' + 1;
// numberString now equals '11', not '2' or 2
const otherExample = 'hello' + 1;
// otherExample now equals 'hello1'

If you have a string stored inside a variable, you can also combine it with another string using the += operator, like this:

let greeting = 'hello';
greeting += ' world';
// greeting = 'hello world'

The += operator takes the string on the right, adds it to the string inside the variable, and stores the new value inside the same variable.

Demo

Exercises

Try the following statements in the console:

"Hello " + "world"

'1' + '1'

'1' + 1
const firstString = "Hello ";
const secondString = "world";
const firstPlusSecondString = firstString + secondString;
let firstString = "hello";
firstString += " world";

References

String literals on MDN

Back to: JavaScript Reference > JS Data Types