JavaScript Program To Add Two Numbers

In this post, we will learn how to write a program to add two numbers in JavaScript.

JavaScript Program To Add Two Numbers

We will be writing two different programs to add two numbers.

  1. By Pre-defined Input
  2. By User Input

So, without further ado, let’s begin this tutorial.

JavaScript Program To Add Two Numbers

// JavaScript Program To Add Two Numbers
// Define variable with integers
var num1 = 2; 
var num2 = 3;

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

// display output
console.log("The Sum of " + num1 + " and " + num2 + " is: " + sum);

Output

The Sum of 2 and 3 is: 5

JavaScript Program To Add Two Numbers with User Input

// Take user input
var num1 = parseInt(prompt("Enter first number: "));
var num2 = parseInt(prompt("Enter second number: "));
 
// Add two numbers
var sum = num1 + num2;
 
// Display output
console.log("The sum of " + num1 + " and " + num2 + " is: " + sum);

Output

The sum of 5 and 7 is: 12

How Does This Program Work ?

var num1 = parseInt(prompt("Enter first number: "));
var num2 = parseInt(prompt("Enter second number: "));

In this program, the user is asked to enter two numbers.  Here, prompt() is used to take input from the user.

The prompt() method displays a dialog box that prompts the visitor for input. The parseInt() function is used to convert strings into integers.

// Add two numbers
var sum = num1 + num2;

Here, we have used + operator to add two or more numbers.

// Display output
console.log("The sum of " + num1 + " and " + num2 + " is: " + sum);

Finally, the sum of two numbers is displayed to the user using the console.log() method. 

Conclusion

I hope after going through this post, you understand how to add two numbers in JavaScript.

If you have any doubt regarding the program, feel free to contact us in the comment section. We will be delighted to help you.

Also Read:

Leave a Comment

Your email address will not be published. Required fields are marked *