JS Example for Beginners: JavaScript Program to Add Two Numbers

Hits: 10

(JavaScript programming Example for Beginners)

JavaScript Program to Add Two Numbers

In this example, you will learn how to add two numbers and display their sum using various methods in JavaScript.


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

Example 1: Add Two Numbers


let num1 = 5;
let num2 = 3;

// add two numbers
let 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
let num1 = prompt('Enter the first number ');
let num2 = prompt('Enter the second number ');

//add two numbers
let 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 input two numbers. Here, prompt() is used to take inputs from the user.

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

Then, the sum of the numbers is computed.

let 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.

 

JS Example for Beginners: JavaScript Program to Add Two Numbers

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.