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

Let's say we have a code snippet that produces some surprising results. First, the modulo operator works with strings (unexpectedly). Second, concatenation of two strings produces awkward results.

We need to explain why JavaScript behaves this way through type coercion.

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

What is Type Coercion?

Type coercion is JavaScript's automatic conversion of one data type to another. This happens implicitly when operators expect different types than what's provided.

Key coercion rules:

  • To String: When using binary + with strings
  • To Number: When using arithmetic operators (-, *, /, %) or unary +
  • To Boolean: When using logical operators (&&, ||, !)

Important: Unary + has higher precedence than binary +.

Code Breakdown

Line 2: String Modulo Operation

const numStr = '127';
const result = numStr % 5;
console.log(typeof numStr, typeof result);
console.log(result);
string number
2

The % operator triggers numeric coercion. JavaScript converts '127' to 127, then calculates 127 % 5 = 2.

Line 5: Double Plus Confusion

const firstName = 'Armaan';
const lastName = 'Malik';
// This is: firstName + (+lastName)
const fullName = firstName + + lastName;
console.log('+lastName =', +lastName);
console.log('fullName =', fullName);
+lastName = NaN
fullName = ArmaanNaN

Due to operator precedence:

  1. +lastName attempts to convert 'Malik' to a number ? NaN
  2. 'Armaan' + NaN converts NaN to string ? 'ArmaanNaN'

More Type Coercion Examples

console.log('5' - 3);        // 2 (string to number)
console.log('5' * '2');      // 10 (both to numbers)  
console.log('hello' - 1);    // NaN (invalid conversion)
console.log(true + 1);       // 2 (boolean to number)
console.log('5' + 3);        // "53" (number to string)
2
10
NaN
2
53

Comparison Table

Operator Coercion Type Example Result
%, -, *, / To Number '10' % 3 1
+ (binary with string) To String '5' + 3 '53'
+ (unary) To Number +'42' 42

Conclusion

JavaScript's type coercion explains why % works on strings (converts to numbers) and why firstName + + lastName produces unexpected results due to operator precedence. Understanding coercion helps predict JavaScript's behavior in edge cases.

Updated on: 2026-03-15T23:18:59+05:30

438 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements