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.
Here’s the problem code −
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);
modulo result: 2 full name: ArmaanNaN
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.
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;
fullName = ArmaanNaN