JavaScript
In this tutorial we will learn about JavaScript arithmetic operators.
In JavaScript like other programming language we use different arithmetic operators to do maths.
Following is the list of arithmetic operators.
Operator | Symbol | Example |
---|---|---|
Addition | + | 1 + 2 Answer: 3 |
Subtraction | - | 1 - 2 Answer: -1 |
Multiplication | * | 4 * 5 Answer: 20 |
Division | / | 10 / 2 Answer: 5 |
Modulus (to get remainder) | % | 5 % 2 Answer: 1 (remainder) |
In the following example we are adding the value of two variables.
var x = 10;
var y = 20;
var sum = x + y;
console.log(sum); //this will print 30
In the following example we are subtraction the value of two variables.
var x = 10;
var y = 20;
var diff = x - y;
console.log(diff); //this will print -10
In the following example we are dividing the value of two variables.
var x = 4;
var y = 2;
var di = x / y;
console.log(di); //this will print 2
In the following example we are multiplying the value of two variables.
var x = 4;
var y = 2;
var mul = x * y;
console.log(mul); //this will print 8
In the following example we are finding the reaminder by using mudulus operator.
var x = 4;
var y = 2;
var mod = x % y;
console.log(mod); //this will print 0 as there is no remainder
In JavaScript and in other programming languages incrementing and decrementing value of a variable by 1 is very common.
In the following example we are incrementing the value of variable x by 1.
var x = 10;
x = x + 1;
console.log(x); //this will print 11
In the following example we are decrementing the value of variable x by 1.
var x = 10;
x = x - 1;
console.log(x); //this will print 9
Another way to accomplish this task is by using the increment and decrement operator.
In the following example we are incrementing the value of variable x by 1.
var x = 10;
x++;
console.log(x); //this will print 11
In the following example we are decrementing the value of variable x by 1.
var x = 10;
x--;
console.log(x); //this will print 9
ADVERTISEMENT