Arithmetic in JavaScript

In this tutorial, you will learn how to use a range of arithmetic operators in JavaScript to assign values, modify variables and perform mathematical calculations.

If you have created your own variables and assigned them each a value (such as a string or integer), then you will already be familiar with the assignment operator which is a single = (equals sign).

Arithmetic operators include:

Addition +
Subtraction
Division /
Multiplication *
Modulus %
Equals =

There are other arithmetic operators and functions (including exponentiation and square root) shown in the video and the sample code below.

The code below shows how you can use a range of operators when working variable assignments and calculations.

Here is the HTML code:

<html>
    <head>
        <title>Arithmetic</title>

        <script src="script.js"></script>
    </head>

    <body>
        
    </body>
</html>

And here is the JavaScript code (including comments explaining each line of code):

// Arithmetic operators

var x = 10; // assignment

console.log(10+5); // addition
console.log(10-5); // subtraction
console.log(10/5); // division
console.log(10*5); // multiplication

console.log(5%2); // modulus (remainder of division)

x = x + 1; // increase x by 1 (long method)
console.log(x);

x++; // increment (increase x by 1)
console.log(x);

x--; // decrement (decrease x by 1)
console.log(x);

x += 5; // compound addition (increase x by 5 - short method)
console.log(x);

x -= 5; // compound subtraction
console.log(x);

x *= 5; // compound multiplication
console.log(x);

x /= 5; // compound division

console.log(5**2); //exponentiation (raises 5 to power of 2)
console.log(Math.pow(5,2)); // using exponentiation function

console.log(Math.sqrt(4)); // square root

console.log((5 + 10) / 2); // grouping numbers using parantheses

Next tutorial: Strings

Leave a Reply