CodeBlanks Logo Icon CodeBlanks

String concatenation

Learn to concatenate strings with + and the common mistakes around it.

Joining strings with +

You use the + operator to glue two strings together. This is called concatenation.

For example "Alex" + " " + "Smith" gives "Alex Smith". Without a space the strings stick directly: "Alex" + "Smith" becomes "AlexSmith".

You can chain many pieces with + in a row. The operation runs left to right; parentheses change the order.

Adding a string and a number

The + operator joins two strings; but if one side is a number JavaScript checks a rule. When either side is a string, + performs concatenation and the number is turned into a string.

For example "Result: " + 5 gives "Result: 5". The number is first converted to a string and then joined.

When both sides are numbers normal addition happens: 3 + 5 → 8. Use typeof to see which type you are dealing with.

Practice Concatenate the full name

Declare firstName as "Alex" and lastName as "Smith". Build fullName as firstName + " " + lastName. Log fullName with console.log.

Starter code

script.js
// Combine first, last and full name and log it

Sample solution

script.js
const firstName = "Alex";
const lastName = "Smith";
const fullName = firstName + " " + lastName;
console.log(fullName);

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does "Alex" + " " + "Smith" give?

script.js
console.log("Ayşe" + " " + "Yılmaz");
  • "Alex Smith" Correct answer
  • "AlexSmith"
  • "Alex+Smith"
  • "Alex" "Smith"

Explanation: + pastes each piece in order; the middle " " space ends up in the result.

2 Concatenate the score

Question
const score = 90; const message = "Skor: " + ____;
Answer
const score = 90; const message = "Skor: " + score;

Explanation: You can add the number variable directly with +; JavaScript converts it to a string.

3 Match each expression to its result

Term Meaning
"a" + "b" "ab"
"x" + 5 "x5"
3 + 5 8
"3" + "5" "35"

4 What does "Value: " + 5 give?

script.js
console.log("Değer: " + 5);
  • 10
  • "Value: 5" Correct answer
  • "Value: " + 5
  • "Value: "

Explanation: With a string on one side, + concatenates; 5 is turned into a string and appended.

All lessons in Beginner