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 +
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:


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


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)

x++; // increment (increase x by 1)

x--; // decrement (decrease x by 1)

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

x -= 5; // compound subtraction

x *= 5; // compound multiplication

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