Write a JavaScript program to calculate the sum of two integers and display the results. In this tutorial, we will show you the two examples of adding numbers.
JavaScript Program to Add Two Numbers
In this JavaScript program, we will calculate the sum of to number and print the results on the console. Here we will use the common
sign to add numbers.
// define variable with integers var num1 = 3; var num2 = 2; // add two numbers var sum = num1 num2; // Show the results console.log(‘The sum is: ‘ sum); |
Output
The sum is: 5
Here we have defined two variables with static integer values. Then calculate the sum of both values and store them in a third variable. Finally, the result is displayed on the console.
Another Example with User Input
Let’s consider another example to calculate the sum of values based on user input. First, have a look at the below program.
// Take user input var num1 = window.prompt(“Enter first number: “); var num2 = window.prompt(“Enter second number: “); // Convert string to integer var x = parseInt(num1); var y = parseInt(num2); // add two numbers var sum = num1 num2; // Show the results alert(‘The sum is: ‘ sum); |
Output will be shown in a popup:
The sum is: 5
This program takes input from user. Here the window.prompt() function create a popuop box in browser to accept input. This input is in string format. So next, we use parseint() function to convert a string value to a integer.
Finally, calculate the sum of both integers and print the results. This time the results will be shown in a popup box.