The first, and arguably the most common method is to use the addition (
+) operator as shown below.
let num1 = 5; let num2 = 10; let sum = num1 + num2; console.log("The sum of " + num1 + " and " + num2 + " is " + sum);
+ operator directly adds the numbers to provide their sum.
In the below example, we begin by defining two variables (num1 and num2) and assigning them the values of 7 and 10, respectively.
We then use the
"+" operator to add num1 and num2 and store the result in a variable named sum. Finally, we log the value of the sum to the console, which should output 17.
const num1 = 7; const num2 = 10; const sum = num1 + num2; console.log(sum);
In the below example, we first convert the strings “7” and “10” to numbers using either the
We then use the
"+" operator to add the two numbers and store the result in a variable named sum. Finally, we log the value of the sum to the console, which should output 17.
const num1 = "7"; const num2 = "10"; const sum = Number(num1) + Number(num2); console.log(sum);
Finally, we can use the
parseFloat() function to add two numbers, as shown below.
const num1 = "7"; const num2 = "10"; const sum = parseFloat(num1) + parseFloat(num2); console.log(sum);
Just like with the
Number() function, we’re converting the strings “7” and “10” to numbers using the
parseFloat() function. We then use the
"+" operator to add the two numbers together and store the result in a variable named sum. Finally, we log the value of the sum to the console, which should output 17.
Note that we can only add two numbers already in numeric format. If you’re adding numbers that are stored as strings (e.g., “7” and “10”), you’ll need to convert them to numbers first before adding them together.
The program can be implemented in different ways, such as using HTML input fields to get user input, using the
prompt() function to get user input, or use predefined values to add two numbers.
Please tell us in the comment box if you have any methods we can explore.