JavaScript program to perform arithmetic operations using Functions | Code

  • by

The JavaScript Arithmetic Operators include operators like Addition, Subtraction, Multiplication, Division, and Modulus. You can use a single function for multiple functions to perform arithmetic operations in JavaScript.

The below table shows the JavaScript Arithmetic Operators with examples.

OperatorsOperationExample
+Addition10 + 2 = 12
Subtraction10 – 2 = 8
*Multiplication10 * 2 = 20
/Division10 / 2 = 5
%Modulus – It returns the remainder after the division10 % 2 = 0 (Here remainder is zero). If it is 10 % 3 then it will be 1.

JavaScript program to perform arithmetic operations using Functions

simple example code has 2 input fields and 5 buttons.

<!DOCTYPE html>
<html>
<body>
  <script type="text/javascript">
    function multiply(){
      a=Number(document.my_cal.first.value);
      b=Number(document.my_cal.second.value);
      c=a*b;
      document.my_cal.total.value=c;
    }

    function addition(){
      a=Number(document.my_cal.first.value);
      b=Number(document.my_cal.second.value);
      c=a+b;
      document.my_cal.total.value=c;
    }


    function subtraction(){
      a=Number(document.my_cal.first.value);
      b=Number(document.my_cal.second.value);
      c=a-b;
      document.my_cal.total.value=c;
    }


    function division(){
      a=Number(document.my_cal.first.value);
      b=Number(document.my_cal.second.value);
      c=a/b;
      document.my_cal.total.value=c;
    }

    function modulus(){
      a=Number(document.my_cal.first.value);
      b=Number(document.my_cal.second.value);
      c=a%b;
      document.my_cal.total.value=c;
    }
  </script>

  <!-- Opening a HTML Form. -->
  <form name="my_cal">

    <!-- Here user will enter 1st number. -->
    Number 1: <input type="text" name="first">
    
    <br>

    <!-- Here user will enter 2nd number. -->
    Number 2: <input type="text" name="second">

    <br><br>

    <input type="button" value="ADD" onclick="javascript:addition();">
    <input type="button" value="SUB" onclick="javascript:subtraction();">
    <input type="button" value="MUL" onclick="javascript:multiply();">
    <input type="button" value="DIV" onclick="javascript:division();">
    <input type="button" value="MOD" onclick="javascript:modulus();">
   
    <br><br>

    <!-- Here result will be displayed. -->
    Get Result: <input type="text" name="total">

  </body>
  </html>

Output:

JavaScript program to perform arithmetic operations using Functions

Do comment if you have any doubts or suggestions on this JS arithmetic operations topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.