JavaScript Program to Add Two Numbers

To understand this example, you should have the knowledge of the following JavaScript programming topics:


We use the + operator to add two or more numbers.

Example 1: Add Two Numbers

const num1 = 5;
const num2 = 3;

// add two numbers
const sum = num1 + num2;

// display the sum
console.log('The sum of ' + num1 + ' and ' + num2 + ' is: ' + sum);

Output

The sum of 5 and 3 is: 8

Example 2: Add Two Numbers Entered by the User

// store input numbers
const num1 = parseInt(prompt('Enter the first number '));
const num2 = parseInt(prompt('Enter the second number '));

//add two numbers
const sum = num1 + num2;

// display the sum
console.log(`The sum of ${num1} and ${num2} is ${sum}`);

Output

Enter the first number 5
Enter the second number 3
The sum of 5 and 3 is: 8

The above program asks the user to enter two numbers. Here, prompt() is used to take inputs from the user. parseInt() is used to convert the user input string to number.

const num1 = parseInt(prompt('Enter the first number '));
const num2 = parseInt(prompt('Enter the second number '));

Then, the sum of the numbers is computed.

const sum = num1 + num2;

Finally, the sum is displayed. To display the result, we have used the template literal ` `. This allows us to include variables inside strings.

console.log(`The sum of ${num1} and ${num2} is ${sum}`);

To include variables inside ``, you need to use the ${variable} format.

Note: Template literals was introduced in ES6 and some browsers may not support them. To learn more, visit, JavaScript template literals support.

Before we wrap up, let’s put your knowledge of JavaScript Program to Add Two Numbers to the test! Can you solve the following challenge?

Challenge:

Write a function to add two numbers.

  • Return the sum of num1 and num2.
  • For example, if num1 = 4 and num2 = 5, the expected output is 9.
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges