Why does JavaScript return 23 instead of 5?
If "2" + "3" produces "23", both values are text. For numeric addition, convert the inputs and validate them before using the result.
Published by Projet Carthage · Updated
Concepts & Theory
For simple values, + can add numbers or join text. 2 + 3 is 5; "2" + "3" is "23". "2" + 3 also concatenates because a string is involved.
Start debugging with typeof: console.log(typeof value) distinguishes "string" from "number". A value read through input.value is a string even when the field displays digits. Convert it explicitly with Number.
Conversion alone is not always enough: Number("abc") produces NaN, while Number("") and Number(" ") produce 0. If an empty input is not valid, check trim() before conversion.
The example rejects empty strings, converts both numbers and checks that they are finite. It then returns their sum. Test a normal case, a decimal, an empty input and text.
As a follow-up exercise, make the function accept only positive integers. Decide what should happen for zero, negative numbers and decimals before writing the condition.
Code Example
Try this examplefunction addInputs(left, right) {
if (left.trim() === "" || right.trim() === "") {
throw new Error("Empty input");
}
const a = Number(left);
const b = Number(right);
if (!Number.isFinite(a) || !Number.isFinite(b)) {
throw new Error("Invalid number");
}
return a + b;
}
console.log(addInputs("2", "3")); // 5
console.log(addInputs("2.5", "3")); // 5.5
try {
addInputs("", "3");
} catch (error) {
console.log(error.message); // Empty input
}Common Pitfalls & Mistakes
✗ Converting too late
Number("2" + "3") // 23Number("2") + Number("3") // 5In the first case, concatenation already happened. Convert each operand before adding.
✗ Ignoring invalid input
Number("abc") + 3 // NaNconst value = Number("abc");
console.log(Number.isFinite(value)); // falseNaN does not automatically throw an exception. Add validation and a clear error message.
Frequently Asked Questions
Should I use Number or parseInt?▾
Number converts the whole value and preserves decimals. parseInt reads an integer prefix: parseInt("2.5", 10) is 2. Number better matches the goal of this numeric form.
Does changing const to let fix it?▾
No. const and let govern reassignment; they do not turn a string into a number. Inspect the value’s type and convert explicitly.
Master JavaScript with interactive exercises
Complete hands-on code challenges in your browser with real-time feedback and progressive hints.
