ENOTES

Adding two number in JavaScript

access_time Mar 05, 2022 remove_red_eye 12130

Adding two number in JavaScript is fairly easy. We have to use arithmetic operator to perform mathematical addition. Addition can be performed directly by assigning value to a variable but this method will not allow user to enter any number they want. So, we can use HTML text box and button to call a JavaScript function. Inside JS function we will retrieve values entered inside text box.

Adding two number directly

<HTML>
<HEAD><TITLE>Addition</TITLE></HEAD>
<BODY>
<SCRIPT>
var a=3, b=2, c=a+b;
document.write(c);
</SCRIPT>
</BODY>
</HEAD>

The above program will display 5 in the browser. The output is always fixed since, it does not allow user to enter number in the browser. So, following method is recommended to make interactive program.

Adding two number in JavaScript

<HTML>
<HEAD><TITLE>Addition</TITLE></HEAD>
<BODY>
<INPUT type=“text” id=“first”>
<INPUT type=“text” id=“second”>
<INPUT type=“button” value = “press” onclick = “sum( )”>

<SCRIPT>
function sum( )
{
var a = document.getElementById(“first”).value;
var b = document.getElementById(“second”).value;
var c = parseInt(a) + parseInt(b);
document.write(c);
}
</SCRIPT>
</BODY>
</HEAD>

The above program will allow user to enter two number in the two text box. Once the user click the button the value entered inside box are passed to JS function through onclick event which calls the sum( ) function. Inside sum( ) function values are assigned to variable ‘a’ and ‘b’. The sum is calculated and assigned to variable ‘c’. parseInt is used to make value entered inside text box to Integer.