The Weirdness of JavaScript: Why Does 1 + ‘1’ Equal 11?
Member-only story
JavaScript is a powerful and flexible language, but it’s also known for its quirks and odd behavior.
One of the most confusing aspects for beginners (and sometimes even experienced developers) is how JavaScript handles type coercion — the automatic conversion of values from one type to another.
In this blog, we’ll explore some of the most puzzling behaviors in JavaScript, such as why 1 + 1 equals 2, but 1 + ‘1’ equals ‘11’.
Let’s dive into the weirdness!
1. Type Coercion: Numbers + Strings = Strings
One of the first things that can confuse JavaScript developers is how the + operator behaves differently when working with numbers and strings.
Example:
In the first example, both operands are numbers, so JavaScript performs basic arithmetic and adds them together, resulting in 2.
In the second example, however, JavaScript sees that one of the operands (’1') is a string. Instead of adding the numbers, it converts the number ‘1’ into a string and concatenates the two strings…