Why JavaScript Says 5 + 5 = 55 (and How to Fix It)
You build a small calculator in JavaScript. Two input boxes, one button. You type 5 in the first box, 5 in the second, click the button, and the page says 55 . Not 10. If that just happened to you, nothing is wrong with your maths or your computer. It’s one of the most common beginner bugs in JavaScript, and it takes one line to fix once you know why it happens. This guide explains why JavaScript…
In this account, we explore a common beginner bug in JavaScript that occurs when building a simple calculator. When users type numbers into the input boxes and click the calculate button, the result displayed is 55 instead of the expected 10. This issue arises because JavaScript treats the input values as text (strings) rather than numbers.
To rectify this bug and correctly calculate the sum of two numbers, you need to convert the strings into numbers before adding them. Three methods are presented for accomplishing this task, namely parseInt(), Number(), and valueAsNumber(). Intended for whole numbers, Number() is the preferred choice for calculations involving decimals or more complex numeric inputs.
Additionally, the article emphasizes the importance of checking for invalid inputs, such as non-numeric values or empty boxes, using isNaN() and trimming whitespace. These checks ensure that your calculator provides accurate results and prevents display errors. The article also highlights the occurrence of this bug in other scenarios, such as using prompt() for user input or retrieving data from localStorage or APIs, which may return strings in certain cases.
By being aware of this issue and employing the appropriate methods for converting text to numbers, you can build a robust and functional calculator in JavaScript.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.