Create a simple function with parameters and use the + operator to add two or more numbers in the JavaScript function.
This code snippet is used to find the sum of two integer numbers using the JavaScript function.
<script>
function add(){
const num1 = 5;
const num2 = 3;
// add two numbers
const sum = num1 + num2;
// display the sum
console.log('The sum of ' + num1 + ' and ' + num2 + ' is: ' + sum);
}
// call function
add();
</script>
Addition of two numbers in JavaScript using functions Example
Let’s see HTML examples code:-
Add Two Numbers with parameters
<!DOCTYPE html>
<html>
<head>
<script>
function sum(a, b){
var c = a+b;
return c;
}
alert(sum(2,2));
</script>
</head>
<body>
</body>
</html>
Output:
Add Two Numbers Entered by the User
Add two integer numbers and display the result in textbox with JavaScript.
<!DOCTYPE html>
<html>
<body>
<div class="container-fluid">
<input type="text" name="number1" id="number1"> <br>
<input type="text" name="number2" id="number2"><br>
<button type="button" onclick="submit1()">submit</button><br>
<p id="result"></p>
</div>
<script>
function submit1(){
var a = document.getElementById("number1").value;
var b = document.getElementById("number2").value;
var c = parseInt(a) + parseInt(b);
document.getElementById("result").innerHTML="Sum of number is:" + c;
}
</script>
</body>
</html>
Output:
Do comment if you have any doubts on this topic and code. Suggestions are always welcome.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version