Plus Operator in JavaScript

The JavaScript + operator indeed serves a dual purpose: it can perform addition between numbers or concatenation between strings. JavaScript determines which operation to perform based on the data types of the values being used with the operator. Let’s look at a few examples:

1. Number Addition

When the + operator is used between two numbers, it performs arithmetic addition:

1
2
3
4
let a = 5;
let b = 10;
let sum = a + b;
console.log(sum);  // Outputs: 15

2. String Concatenation

When the + operator is used between two strings, it concatenates (joins together) the strings:

1
2
3
4
let str1 = "Hello, ";
let str2 = "world!";
let message = str1 + str2;
console.log(message);  // Outputs: "Hello, world!"

3. Mixing Numbers and Strings

When the + operator is used between a number and a string, JavaScript converts the number into a string and then performs string concatenation:

1
2
3
4
let num = 100;
let str = "The number is: ";
let result = str + num;
console.log(result);  // Outputs: "The number is: 100"

This conversion is known as “type coercion”, where JavaScript automatically converts one type to another. In the case of the + operator, it prefers string concatenation over numeric addition if any of the operands are strings.

Note: It’s important to remember that only the + operator behaves this way. Other arithmetic operators (-, *, /, %) always convert strings to numbers and perform the numerical operation or result in NaN (Not a Number) if the string can’t be converted to a number.