String Operators Explained
String operators are used to:
- Combine (concatenate) strings
- 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:
- You must manually add spaces using
" " - 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:
- 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:
- Use backticks:
` - 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:
- Cleaner and more readable
- No need for
+ - 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 + 2 = 33 + "3"→ string →"33"
Case 2:
console.log("1" + 2 + 3);
Output:
"123"
Explanation:
"1" + 2→"12""12" + 3→"123"
Key Rules to Remember
- If any operand is a string, result becomes a string
- JavaScript evaluates left to right
+works as:- Addition → with numbers
- Concatenation → with strings
Common Mistakes
- Forgetting spaces:
"Hello" + "World" // HelloWorld
- Confusion in mixed types:
1 + "2" + 3 // "123"
- Overusing
+instead of template literals
Best Practice
Use Template Literals for clean code:
let message = `${name} is ${age} years old`;