JavaScript Lesson 5: Arithmetic Operations in JavaScript

  • <Lesson 5> [Contents] <Lesson 6>

    5.1 Arithmetic Operations in JavaScript

    JavaScript is not just a scripting language, it can also perform arithmetic operations. On top of that, it can interact with online users by receiving data from them, operate on the data and then display the output to the users. The four basic arithmetic operators in JavaScript are shown in the following table:

    Operation Operator
    Addition +
    Subtraction
    Multiplication *
    Division /

    Let us construct our first arithmetic program in JavaScript. You can either use a text editor such as notepad to type in the statements. You can also use Microsoft Frontpage or Dreamweaver to do the job. However, the best free editor I would recommend is Notepad++, which you can download from  https://notepad-plus-plus.org/ .


    Now, key in the following lines of statements.

    <HTML><HEAD>
    <Script Language="JavaScript">
    var           Number1, // this is the first string input by the user
    Number2 , // this is the second string input by the user
    Num1 , // numeric value converted from Number1
    Num2, // numeric value converted from Number2
    sum,
    difference ,
    product,
    quotient;
    Number1=window.prompt("Enter your first Integer","0");
    Number2=window.prompt("Enter your second integer","0");
    Num1=parseInt(Number1);
    Num2=parseInt(Number2);
    sum=Num1+Num2;
    difference=Num1-Num2;
    product=Num1*Num2;
    quotient=Num1/Num2;
    document.writeln(Number1+"+"+Number2+"="+sum+"<BR>");
    document.writeln(Number1+"-"+Number2+"="+difference+"<BR>");
    document.writeln(Number1+"x"+Number2+"="+product+"<BR>");
    document.writeln(Number1+"/"+Number2+"="+quotient);</Script>
    
    

    Click Testing Page to view the output



    <Lesson 4> [Contents] <Lesson 6>

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on Reddit