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:
|
|
2. String Concatenation
When the +
operator is used between two strings, it concatenates (joins together) the strings:
|
|
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:
|
|
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.