Skip to main content

String Operator in JavaScript

In JavaScript, the string operator (+) is used to concatenate two or more strings. It can also be used to concatenate a string with other data types by implicitly converting them to strings.

Types of String Operator in JavaScript

The following are the types of string operators in JavaScript:

String Concatenation Operator (+)

The string concatenation operator (+) is used to concatenate two or more strings.

String Concatenation Operator
let str1 = "Hello";
let str2 = "World";
console.log(str1 + " " + str2); // Output: Hello World

Implicit Type Conversion

The string operator (+) can also be used to concatenate a string with other data types by implicitly converting them to strings.

Implicit Type Conversion
let str = "Hello";
let num = 123;
console.log(str + num); // Output: Hello123

String Concatenation with Assignment

The string concatenation operator (+) can be combined with the assignment operator (=) to concatenate and assign the result to a variable.

String Concatenation with Assignment
let str = "Hello";
str += " World";
console.log(str); // Output: Hello World

String Concatenation with Template Literals

The string concatenation operator (+) can be replaced with template literals to concatenate strings in a more readable way.

String Concatenation with Template Literals
let str1 = "Hello";
let str2 = "World";
console.log(`${str1} ${str2}`); // Output: Hello World

In this example, the ${} syntax is used to embed expressions within the string. The expressions are evaluated and concatenated with the surrounding string.

In the above examples, the string concatenation operator (+) is used to concatenate two strings, implicitly convert a number to a string, concatenate and assign the result to a variable, and concatenate strings using template literals.

📝 Note

The string concatenation operator (+) can also be used to concatenate strings with other data types, such as numbers, booleans, and objects, by implicitly converting them to strings.

For example, console.log("Hello" + 123); will output Hello123.

String template literals can also be used to concatenate strings in a more readable way. For example, console.log(`${"Hello"} ${"World"}`); will output Hello World. It is intruduced in ECMAScript 6 (ES6).

When using template literals, expressions within `${}` are evaluated and concatenated with the surrounding string.

Conclusion

The string operator (+) is used to concatenate two or more strings. It can also be used to concatenate a string with other data types by implicitly converting them to strings. It can be combined with the assignment operator (=) to concatenate and assign the result to a variable. It can also be replaced with template literals to concatenate strings in a more readable way.