After you declare and assign numerical values to your variables, you can perform mathematical operations on those values using JavaScript's built-in arithmetic operators. As per discussion for this page, we will cover only four basic JavaScript mathematical operators:
In JavaScript, like other programming languages, you can build complex mathematical expressions using combination of the basic mathematical operators mentioned above. Consider the following as an example:
50 + 40 / 10
The above expression says divide 40 by 10 and add this result to 50. The result would be 54. Remember division and multiplication operators has higher precedence than addition and subtraction operators.
The following JavaScript code shows some examples of mathematical operations:
<script language="javascript">var x, y, z;x = 50;y = 10;document.write ("x = "); // prints a messagedocument.write (x); // prints the value of xdocument.write (", y = "); // prints a messagedocument.write (y); // prints value of ydocument.write ("<br>x + y is "); // prints a string messagez = x + y; // adds 50 + 10 and assigns the result to the variable zdocument.write (z); // prints the value of z, which is 60document.write ("<br>x - y is "); // prints a stringz = x - y; // substracts x from y and assigns the resulting value to zdocument.write (z); // prints the value of z, 40document.write ("<br>x * y is "); // prints a messagez = x * y; // multiplies x * y and assigns result to zdocument.write (z); // prints z, 500document.write ("<br>x / y is "); // prints a messagez = x / y; // dividies x by y assigns result to zdocument.write (z); // prints the value of z, 5</script>
In this JavaScript code above, we declare and use three numerical variables. The example has many print statements. The first a few print statements print the values of x and y. Then, we print the value of z, after each mathematical operation. The following shows the output of the above code: