JS program to perform all arithmetic operations

Addition, Subtraction, Division, and Multiplication in Java Script. Below are some Java Script examples to perform arithmetic operations. In example 1, we will create a simple GUI application to perform arithmetic operations using HTML and JS. In other example, you will see arithmetic operations with the console.

JS program to perform all arithmetic operations

Steps

  • Take user input
  • Use function Calc()
  • Print result

Program to perform all arithmetic operations in JS using textbox

<!DOCTYPE html>
<html>
<head>
    <title>Javscript Calculate</title>
    <meta charset="windows-1252">\

    <script>
        function calc()
        {
            var n1 = parseFloat(document.getElementById('n1').value);
            var n2 = parseFloat(document.getElementById('n2').value);
            var oper = document.getElementById('operators').value;

            if (oper === '+') 
            {
                 document.getElementById('result').value=n1+n2;
            }
            if (oper === '-') 
            {
                 document.getElementById('result').value=n1-n2;
            }
            if (oper === '/') 
            {
                 document.getElementById('result').value=n1/n2;
            }
            if (oper === '*') 
            {
                 document.getElementById('result').value=n1*n2;
            }
        }
    </script>
</head>
<body>
    <input type="text" id="n1"/><br/><br/>
    <input type="text" id="n2"/><br/><br/>

    <select id="operators">
        <option value="+">+</option>
        <option value="-">-</option>
        <option value="/">/</option>
        <option value="*">*</option>
    </select>

    <button onclick="calc();">=</button>
    <input type="text" id="result"/>
</body>
</html>

Output

Program to perform all asthmatic operations using JS functions

<!DOCTYPE html>
<html>
<head>
    <title>ARITHMATIC OPERATIONS</title>
</head>
<body>
<script>
    //addition
    var a = 100;
    var b = a + 200 +100;
    //alert(b);

    //substraction
    var c = 100 - 50;
    //alert (c);

    //multiplication
    var m = c * 10;
    //alert (m);

    //division
    var d = 500 / 2;
    alert(d);

    //mix
    var combo = 100 + 50 / 2 + 10;
    //alert (combo);
</script>
</body>
</html>

Output

In this way, we learned how to perform arithmetic operations in JS.