CodeBlanks Logo Icon CodeBlanks

String concatenation

JavaScript course · Beginner · Lesson 32/133

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.

Exercise Concatenate the full name

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

Show example solution
const firstName = "Alex";
const lastName = "Smith";
const fullName = firstName + " " + lastName;
console.log(fullName);

Test yourself

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

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

    "Alex Smith" — Correct. + pastes each piece in order; the middle " " space ends up in the result.

  2. Concatenate the score

    const score = 90; const message = "Skor: " + ____;
    Show answer
    const score = 90; const message = "Skor: " + score;
  3. Match each expression to its result

    "a" + "b"
    "ab"
    "x" + 5
    "x5"
    3 + 5
    8
    "3" + "5"
    "35"
  4. What does "Value: " + 5 give?

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

    "Value: 5" — Correct. With a string on one side, + concatenates; 5 is turned into a string and appended.

All lessons in Beginner