Javascript Basics

Javascript Arithmetic Operators

To perform arithmetic operations Javascript has operators that performs the task.

Operators

Addition Operator

As the name says, arithmetic operator performs arithmetic operation. The symbol of addition operator is +

Example

<script>

var num1=10;

var num2=20;

alert(num1+num2);

</script>

Output:30

Subtraction Operator

Subtraction Operator performs subtraction operation. The symbol of subtraction operator is –

Example

<script>

var num1=20;

var num2=10;

alert(num1-num2);

</script>

Output: 10

Multiplication Operator

Multiplication operator performs multiplication operation. The symbol of multiplication operator is *

Example

<script>

var num1=5;

var num2=10;

alert(num1*num2);

</script>

Output: 50

Division Operator

Division operator performs division operations. The symbol of division operator is /

Example

<script>

var num1=100;

var num2=50;

alert(num1/num2);

</script>

Output:2

Modulus Operator

Modulus Operator performs modulus operation. The symbol of modulus operator is %

What is modulus operation?

Modulus operation gives us the remainder of division of two numbers.

Example

<script>

var num1=25;

var num2=10;

alert(num1%num2);

</script>

Looking at the above code we can say the remainder will be 5.

So using Modulus operator, we can get the remainder of division of two numbers.

Increment Operator

To understand what is an Increment Operator, lets consider a simple situation. A requirement came to increment a value by 1 then how could we achieve this?

<script>

var num1=10;

num1=num1+1;

alert(num1);

</script>

Output: 11

Note: In the second line of the above code, we have added 1 to the value of the variable name num1 and then we assigned back to itself that is num1. (num1=num1+1);

Now, the below code is also going to provide us the same result.

<script>

var num1=10;

num1++;

alert(num1);

?>

Output:11

Note: Look at the second line in the above example. There is a double plus symbol beside to the variable name. This double plus sign is known as increment operator.

num1++ is equivalent to num1=num1+1

What does an increment operator do?

An increment operator increments the value of the variable by 1.

Decrement Operator

Decrement operator is similar to increment operator except it decrements the value of the variable by 1. And the symbol for decrement operator is double minus sign —

Example

Decrement the value of variable by 1

<script>

var num1=10;

num1–;

alert(num1);

<script>

Output: 9