JavaScript : Why does % operator work on strings? - (Type Coercion)


Let’s say we have a code snippet here that produces some startling results. Firstly, we see that the modulo operator is working fine with strings as well (surprisingly). Secondly, concatenation of two strings produces awkward results.

We need to explain why JavaScript does so?

Here’s the problem code −

Example

const numStr = '127';
const result = numStr % 5;
const firstName = 'Armaan';
const lastName = 'Malik';
const fullName = firstName + + lastName;
console.log('modulo result: ', result);
console.log('full name: ', fullName);

Output

modulo result: 2
full name: ArmaanNaN

Before jumping into the code, let’s first learn a bit about one of the most fundamental topics of JavaScript → Type Coercion.

Type Coercion

Basically, type coercion is a way used by JavaScript compilers to change one data type into another. Examples of valid type coercion will be changing string to boolean, number to string and so on.

Type coercion is a very vast topic and to restrict the length of this solution we will be exploring only the things used in this code snippet. Out of the two types of type coercion, one that is automatically done by compiler is called implicit type coercion.

It follows −

Any data type (primitive or non-primitive) will be implicitly coerced to −

  • String (when used with binary + operator).

  • Number (when used with arithmetic operators like +, -, /, *,% and only the unary + triggers

Number coercion not binary +, when used with comparison operator, bitwise operator or loose equality operator[==])

  • Boolean (when used with logical operators & | ! )

***Another thing to note is that the precedence of unary (+) operator is higher than the binary (+) operator.

Code Explanation

So, with these things clear, let’s move to the code and go though it line by line −

Line 2 → result = '127' % 5;

Implicit coercion takes in and sees the % operator, because of which it converts String ‘127’ to Number 127 and 2 gets stored in result −

Line 5 → fullName = firstName + + lastName;
fullName = firstName + (+lastName);

In normal course, the computation would have taken place from left to right but because of precedence of unary operator, it gets computed to Number first and the operation becomes like this −

fullName = firstName + NaN;

And then

fullName = ArmaanNaN

Updated on: 18-Aug-2020

210 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements