Explain Codes LogoExplain Codes Logo

Adding two numbers concatenates them instead of calculating the sum

javascript
type-conversion
input-validation
parseint
Anton ShumikhinbyAnton Shumikhin·Aug 13, 2024
TLDR
let sum = +input1.value + +input2.value;

Always prefix inputs with + to swiftly coerce a string into a number, ensuring a quick and accurate addition.

Spot-on type conversion

Straight off the bat, you need to grapple with the hard fact that JavaScript mentally visualizes form inputs as strings. So, to shake it up and have it treat them as numbers, it's high time we performed an explicit conversion.

let number = Number(input); // Protip: If you're feeling adventurous, +input also does the trick.

Conquering whole numbers with parseInt

No journey into the world of numbers would be complete without our trusty sidekick, parseInt(). Let's unleash it on whole numbers, provide a radix (base), which is usually 10, and say adios to any sneaky octal interpretations.

let integer = parseInt(string, 10); // Steer clear of binary black holes and octal octopi.

Float like a float, sting like a parseFloat

Breaking news: parseInt() is no friend of decimals. In decimal situations, call upon parseFloat() to ensure our number remains a smooth and un-rounded floating-point number.

let float = parseFloat(string); // Floating around in the sea of digits, caught parseFloat handed.

Invalid inputs? No problemo!

In an unpredictable universe of user inputs, occasional non-numerical curveballs are par for the course. Here's your magic formula: parseInt(input, 10) || 0. Invalid input? Zilch, zero, nada - the calculation stays robust, and your app sails on!

Visualization

Imagine each number as a unique color: 1️⃣ (red) + 2️⃣ (blue) => 🟣 (purple) // This is what we expect with numbers - their values combine to make a new color (or sum). But in JavaScript, without proper type handling: "1️⃣" (red paint tube) + "2️⃣" (blue paint tube) => "12️⃣" (a tube labeled red-blue) // Instead of mixing paint, we're just sticking tubes next to each other! Only when we pour out the paint and mix them: parseInt("1️⃣", 10) + parseInt("2️⃣", 10) => 3️⃣ (a purple one) // BAM! The numbers add up to become a new color!

The quirks of addition in JavaScript

+ does have baggage!

In JavaScript, + is more than a symbol - it has personality, it's overloaded! Chameleon-like, it changes its behavior based on the datatype of its operand, preferring concatenation when it senses a whiff of string. Duck and type-check!

Good news, strings aren't permanent

HTML form fields, though fond of text, can be coaxed into returning numbers with a sweet little type conversion using utilitarian functions like Number() or parseFloat().

Input validation

Don't let faulty input rain on your astronomical JavaScript parade. Rolling out the red carpet for input validation keeps your data processed strictly numeric and brings in the handyman, user feedback for invalid surprises.

Potential gotchas and their countermeasures

Accidental concatenation

Are your sum displays starting to look like strings of numbers, not real sums? Is JavaScript pulling a fast one on you and skipping type conversion? Could be a sign, you better check!

Integer rounding off your decimals

Are you using parseInt() with decimal numbers and getting odd results? Time to use parseFloat() instead and keep your fractions intact!

Incorrect radix in parseInt

Does parseInt() keep misbehaving even after a stern warning? Check if the radix is 10 and that there aren't any leading zeroes inviting octal trouble.