JavaScript String Operators
String operators are used to combine or update text (strings) in JavaScript. They make it easy to build messages, labels, or any textual content in your programs.
1. Concatenation (+
)
The +
operator can combine (concatenate) two or more strings into a single string.
Example 1: Basic concatenation
let firstName = 'John';
let lastName = 'Doe';
let fullName = firstName + ' ' + lastName;
console.log(fullName); // Output: "John Doe"
Example 2: String + Number
let result = 'Age: ' + 25;
console.log(result); // Output: "Age: 25"
Example 3: Number + String
let result = 25 + ' years';
console.log(result); // Output: "25 years"
2. Append (+=
)
The +=
operator adds a string to an existing string variable, effectively updating it.
Example 1: Appending text
let message = 'Hello';
message += ' World';
console.log(message); // Output: "Hello World"
Example 2: Appending multiple times
let log = 'Start';
log += ' -> Step 1';
log += ' -> Step 2';
console.log(log); // Output: "Start -> Step 1 -> Step 2"
Example 3: Appending numbers
let text = 'Total: ';
text += 100;
console.log(text); // Output: "Total: 100"