JavaScript Code for Adding Two Numbers

Hi, in this post we are going to learn How to add Two Numbers in JavaScript? To understand this example, firstly you have the knowledge of JavaScript Variables and Constants and JavaScript Operators.

Now let's see different examples of JavaScript code for adding two numbers.

JavaScript Code for Adding Two Numbers, Geeks Help, Raju Webdev

Example-1: Add two numbers using + operator 

// variables
const num1 = 4;
const num2 = 20;

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

// displaying the sum
console.log('Sum of two numbers: ' + num1 + ' and ' + num2 + ' is: ' + sum);

Output: Sum of two numbers: 4 and 20 is: 24

Example-2: Add two numbers in JavaScript using prompt

OR

JavaScript to add two numbers in HTML

<!DOCTYPE html>
<html>

<head>
    <title> JavaScript to add two numbers in HTML </title>
</head>

<body>

</body>
<script>
    // taking input numbers from the user
    const num1 = parseInt(prompt('Enter first number: '));
    const num2 = parseInt(prompt('Enter second number: '));

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

    // displaying the sum on browser screen
    document.write('Sum of ' + num1 + ' and ' + num2 + ' is: ' + sum)3
</script>

</html>

In the given program prompt() is used to take the inputs from the user and store it to num1 and num2. And parseInt() is used to convert the user input string to a number.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

Top Post Ad

Below Post Ad