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

#### Example-1: Add two numbers using + operator

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

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

#### JavaScript to add two numbers in HTML

<!DOCTYPE html>
<html>

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

<body>

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

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.

Tags