JavaScript + Operator

The + operator in JavaScript serves multiple purposes. It is primarily used for addition, but it can also be used for string concatenation. Here's how it works:

Addition

When the + operator is used with two numbers, it performs addition. For example:

1let result = 5 + 3; // result is 8

In this case, 5 and 3 are numbers, and the + operator adds them together to produce the result 8.

String Concatenation

If at least one of the operands is a string, the + operator is used for string concatenation.

For example:

1let greeting = "Hello, " + "World!"; // greeting is "Hello, World!"

Here, the + operator concatenates the two strings to create a new string.

Automatic Type Conversion (Type Coercion)

JavaScript performs automatic type conversion (or type coercion) when using the + operator with different data types. Type coercion converts values to a common data type so that they can be operated on. Here's how it works:

Example 1: Number + String

1let result = 5 + "3"; // result is "53"

In this case, the number 5 is automatically converted to a string, and then the two strings are concatenated to produce "53".

Example 2: String + Number

1let result = "5" + 3; // result is "53"

Here, the number 3 is automatically converted to a string, and then the two strings are concatenated to produce "53".

Example 3: Number + Boolean``

1let result = 5 + true; // result is 6

In this case, the boolean value true is automatically converted to the number 1, and then the addition is performed.

What do you think would be the result of following code?

1let num = 10;
2let num2 = 5;
3let str = "Hello";
4
5let first = num + num2 + str;
6let second = str + num + num2;

Here first variable will have 15Hello and second will have Hello105 because of order of operation. The operation evaluates from left to right.