Performing Basic Math in JavaScript

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:

  1. Additionadds two values together; example: 30 + 78.
  2. Subtractionsubtracts one value from another; example: 450 - 21.
  3. Multiplicationmultiplies two values together; example: 120 * 23.
  4. Divisiondivides one value by another; example: 40 / 2.

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 message
document.write (x); // prints the value of x
document.write (", y = "); // prints a message
document.write (y); // prints value of y
document.write ("<br>x + y is "); // prints a string message
z = x + y; // adds 50 + 10 and assigns the result to the variable z
document.write (z); // prints the value of z, which is 60
document.write ("<br>x - y is "); // prints a string
z = x - y; // substracts x from y and assigns the resulting value to z
document.write (z); // prints the value of z, 40
document.write ("<br>x * y is "); // prints a message
z = x * y; // multiplies x * y and assigns result to z
document.write (z); // prints z, 500
document.write ("<br>x / y is "); // prints a message
z = x / y; // dividies x by y assigns result to z
document.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: