Home Courses String Operators Explained

String Operators Explained

String operators are used to:

  1. Combine (concatenate) strings
  2. Join strings with other data types (number, boolean, null, undefined)


String Concatenation (+ Operator)

Definition:

The + operator joins two or more strings.

Example:


let str = "Hello";
let name = "Anil";

let result = str + " " + name;
console.log(result); // Hello Anil

Key Points:

  1. You must manually add spaces using " "
  2. Works with multiple values

Example with multiple values:


let result = str + " " + name + " My age is " + 30;
console.log(result); // Hello Anil My age is 30


String + Other Data Types

When a string is combined with other data types:

  1. Everything converts to a string

Examples:


console.log("Age: " + 25); // "Age: 25"
console.log("Value: " + true); // "Value: true"
console.log("Test: " + null); // "Test: null"
console.log("Data: " + undefined); // "Data: undefined"


Append Operator (+=)

Definition:

Used to add one string into another variable.

Syntax:


variable += value;

Example:


let data1 = "Hello, ";
let data2 = "How are you?";

data1 += data2;

console.log(data1); // Hello, How are you?


Equivalent to:


data1 = data1 + data2;


Template Literals (ES6)

Definition:

A modern way to combine strings without using +

Syntax:

  1. Use backticks: `
  2. Use ${} to insert variables

Example:


let data1 = "Hello,";
let name = "Anil";
let data2 = "How are you?";

let result = `${data1} ${name} ${data2}`;
console.log(result);
// Hello, Anil How are you?

Advantages:

  1. Cleaner and more readable
  2. No need for +
  3. Easy to add spaces and text

Example with extra text:


let result = `${data1} ${name} ${data2}, How about you?`;


Important Interview Concepts

Case 1:


console.log(1 + 2 + "3");

Output:

"33"

Explanation:

  1. 1 + 2 = 3
  2. 3 + "3" → string → "33"

Case 2:


console.log("1" + 2 + 3);

Output:

"123"

Explanation:

  1. "1" + 2"12"
  2. "12" + 3"123"


Key Rules to Remember

  1. If any operand is a string, result becomes a string
  2. JavaScript evaluates left to right
  3. + works as:
  4. Addition → with numbers
  5. Concatenation → with strings


Common Mistakes

  1. Forgetting spaces:
"Hello" + "World" // HelloWorld
  1. Confusion in mixed types:

1 + "2" + 3 // "123"

  1. Overusing + instead of template literals


Best Practice

Use Template Literals for clean code:


let message = `${name} is ${age} years old`;


Share this lesson: