In this example, you will learn how to add two numbers in javascript and return their sum with the help of different methods.
But before going into the example, you must have knowledge of the following JavaScript topics:
To add two or more numbers we use +
operator.
Example 1: Add two numbers in Javascript
const num1 = 5;
const num2 = 5;
// sum two numbers
const sum = num1 + num2;
// display sum
console.log("The sum of " + num1 + " and " + num2 + " is: " + sum);
Output
The sum of 5
and 5
is: 10
Example 2: Add user input numbers in Javascript
// take user input
const num1 = parseInt(prompt("Enter the first number "));
const num2 = parseInt(prompt("Enter the second number "));
// sum two numbers
const sum = num1 + num2;
// display sum
console.log(`The sum of ${num1} and ${num2} is: ${sum}`);
Output
Enter the first number 5
Enter the second number 5
The sum of 5 and 3 is: 10
In the above program, the first two statements are for taking the user inputs using the prompt()
. After taking the user inputs we are converting them from string
to number
using parseInt()
and then we are saving them in variables num1
and num2
.
const num1 = parseInt(prompt("Enter the first number "));
const num2 = parseInt(prompt("Enter the second number "));
After taking inputs we will compute their sum
.
const sum = num1 + num2;
Finally, the sum will be displayed. To display the sum we have used template literals. They are used to include variables inside the strings.
console.log(`The sum of ${num1} and ${num2} is: ${sum}`);
To use string literals we first wrap the string inside ` `
(backticks). And then we will use the ${variable}
syntax to insert the variable inside the string.
Note: Template literals was introduced in ES6 and some browsers may not support them. Please visit JavaScript template literals to learn more.