Arithmetic Operators
Javascript offers a wide range of operators, which are symbols that instruct the compiler to perform specific mathematical or logical manipulations. This tutorial focuses on one of the most commonly used types of operators, the Arithmetic Operators.
What are Arithmetic Operators?
Arithmetic operators are used to perform mathematical operations between numeric operands. The basic arithmetic operators in Javascript include:
- Addition (+)
- Subtraction (-)
- Multiplication (*)
- Division (/)
- Remainder (%)
- Increment (++)
- Decrement (--)
Here's a breakdown of how each of these operators work:
Addition (+)
This operator adds two operands. For example:
let sum = 5 + 3; // sum will be 8
Subtraction (-)
This operator subtracts the second operand from the first. For example:
let diff = 5 - 3; // diff will be 2
Multiplication (*)
This operator multiplies two operands. For example:
let product = 5 * 3; // product will be 15
Division (/)
This operator divides the first operand by the second. For example:
let quotient = 6 / 3; // quotient will be 2
Remainder (%)
This operator returns the remainder left after division of one number by another. For example:
let remainder = 7 % 3; // remainder will be 1
Increment (++)
This operator increases (increments) the value of a variable by 1. There are two types of increment operators: prefix increment (i.e., ++x) and postfix increment (i.e., x++). For example:
let x = 5;
x++; // x will be 6
Decrement (--)
This operator decreases (decrements) the value of a variable by 1. Similar to the increment operator, it also has two types: prefix decrement (i.e., --x) and postfix decrement (i.e., x--). For example:
let x = 5;
x--; // x will be 4
Operator Precedence
In Javascript, multiple operators in the same expression are evaluated according to operator precedence. Multiplication (*), division (/), and remainder (%) operators have higher precedence than addition (+) and subtraction (-). However, you can change the order of operations by using parentheses.
For example:
let result = 5 + 3 * 2; // result will be 11
let resultWithParentheses = (5 + 3) * 2; // resultWithParentheses will be 16
In the first example, multiplication is performed before addition due to higher precedence. In the second example, parentheses change the order, and addition is performed before multiplication.
Conclusion
Arithmetic operators are fundamental to writing any program in Javascript. They allow us to perform mathematical operations and manipulate numeric data. Practice using these operators to become more proficient in Javascript. Happy coding!