Interactive online courses HTML Academy
2026-03-09 12:22 Diff

Each data type supports its own operations. Arithmetic operations are intended for numbers, not strings.

The most important string operation is string joining or concatenation. Example:

var name = 'Muffin'; 'Instructor' + 'Muffin'; // result: 'InstructorMuffin' 'Instructor ' + 'Muffin'; // result: 'Instructor Muffin' 'Instructor ' + name; // result: 'Instructor Muffin'

Concatenation and addition use the same plus sign. But how does JavaScript understand what operation it should use, addition or concatenation? It looks at the types of operands: if they are strings, they are merged; of they are numbers, they are added up.

And we come to a difficult topic here: what happens if the operands are of different types? For example:

'Milk, g: ' + 50; // result: 'Milk, g: 50' '2' * 50; // result: 100

In this case, JavaScript tries to convert the operands into the same type and perform the operation. A corresponding type will be chosen depending on the type of operation.

A plus can be an addition or concatenation sign, but since one of the operands is a string, addition is out of the question. That’s why the number 50 is converted into the string '50' and merged with the string 'Milk, g: '.

The asterisk is a multiplication sign. That is why JavaScript attempts to convert the string '2' into a number and succeeds. Then the numbers 2 and 50 are multiplied and we get 100 as a result.

That’s because JavaScript can change the type of operands on the go, that why it’s called a language with dynamic type casting. Of course, there are a lot of nuances and issues with type casting. We will look at this matter in detail later in the course. Let’s also agree that we won’t have any issues with that in our first programs. They are simple and users enter data carefully.

Let’s go back to concatenation now. What makes it so good? It helps make program messages more informative and “human”. Let’s practice.