String concatenation
Definition
String concatenation is an operation in which two or more strings are joined into one.
Example
const firstName = 'Oleh';
const lastName = 'Kovalenko';
const fullName = firstName + ' ' + lastName;
console.log(fullName); // "Oleh Kovalenko"Here the + operator is used to glue strings together.
JS does not add them as numbers, it joins them, because at least one operand is a string.
Behavior of the + operator
If one of the operands is a string, JS automatically converts the other operand to a string:
'Age: ' + 25; // "Age: 25"
'Answer: ' + true; // "Answer: true"
'Array: ' + [1,2,3]; // "Array: 1,2,3"This is an example of implicit type coercion.
Example with multiple strings
const message = 'Hello, ' + 'world' + '!';
console.log(message); // "Hello, world!"Alternative: template literals
The modern approach (ES6+) is to use backticks `
and embed variables via ${}:
const name = 'Oleh';
const age = 25;
const message = `My name is ${name}, I am ${age} years old.`;
console.log(message); // "My name is Oleh, I am 25 years old."This is also concatenation, but more readable and more powerful. It lets you easily add variables, line breaks and expressions.
Example with line breaks
Before (pre-ES6):
const text = 'First line\n' + 'Second line';With template literals:
const text = `
First line
Second line
`;Concatenation of different types
console.log('5' + 5); // "55"
console.log('true: ' + true); // "true: true"
console.log(1 + '2' + 3); // "123"JS always turns numbers into strings, if at least one operand is a string.
Summary
| Method | Example | Result |
|---|---|---|
The + operator | 'Hello ' + 'World' | 'Hello World' |
| Template literals | Hello ${name} | 'Hello Oleh' |
| Implicit conversion | 'Age: ' + 25 | 'Age: 25' |
In short
Concatenation = joining strings together. Done through
+or template literals...${}.... If at least one operand is a string, JS converts everything to a string.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.