Basics · beginner
JavaScript Program to Add Two Numbers
Add two numbers in JavaScript, read them as input, and see why "2" + "3" gives "23": convert strings with Number() before adding them.
- const and let
- Number()
- the + operator
- template literals
Adding two numbers is the first program most people write, and in JavaScript it comes with a famous surprise: + also joins strings, and input always arrives as a string. "2" + "3" is "23", not 5.
The program reads two lines of input, converts them with Number(), adds them and prints the result with a template literal.
The program
const a = Number(prompt());
const b = Number(prompt());
const sum = a + b;
console.log(`${a} + ${b} = ${sum}`);
console.log("Without Number():", "2.5" + "4.25");2.5
4.252.5 + 4.25 = 6.75
Without Number(): 2.54.25How it works
- prompt() returns the next line of the stdin box as a string, such as "2.5".
- Number() converts the string to a number. It returns NaN ("not a number") when the text is not a valid number.
- a + b adds the two numbers, because both operands are numbers now.
- The template literal (backticks) puts the values into the sentence wherever ${...} appears.
- The last line shows what happens without the conversion: + joins the two strings.
Watch it run line by line
Step through the first two lines and watch a and b appear as numbers (2.5, not "2.5"). Remove Number() and visualize again: the variables become strings and sum becomes "2.54.25".
“Visualize step by step” opens the program in the JavaScript Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.
Another way: Read both numbers from one line
When the input is "2 3" on one line, split it on whitespace and convert each part with map(Number). Destructuring puts the two results into a and b.
const [a, b] = prompt().trim().split(/\s+/).map(Number);
console.log(a + b);2 35Common mistakes
- Adding the strings from prompt() directly: "2" + "3" is "23".
- Using parseInt() for decimals: parseInt("2.5") is 2. Use Number() or parseFloat().
- Not checking for NaN: Number("abc") is NaN, and NaN + 1 is still NaN. Test with Number.isNaN(value).
- Expecting 0.1 + 0.2 to be 0.3: it is 0.30000000000000004. Round for display with toFixed(2).
Try it yourself
- Print the difference, product and quotient as well.
- Show an error message when either input is not a number.
- Add any number of values given on one line with reduce().
Open the program in the JavaScript Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 JavaScript examples, or write your own program in the online JavaScript Compiler.