Arithmetic operations are some of the most basic operations that can be performed in programming. In JavaScript, we have several built-in operators for performing arithmetic operations such as addition, subtraction, multiplication, and division. In this article, we will cover the different arithmetic operators available in JavaScript and how they can be used in programming.
Basic Arithmetic Operators
The basic arithmetic operators in JavaScript are as follows:
+
for addition-
for subtraction*
for multiplication/
for division
Here’s an example of using these operators to perform arithmetic operations:
let x = 10;
let y = 5;
let z = x + y; // Addition
let w = x - y; // Subtraction
let a = x * y; // Multiplication
let b = x / y; // Division
Modulus Operator
Another commonly used arithmetic operator in JavaScript is the modulus operator, represented by the %
symbol. The modulus operator returns the remainder of a division operation.
Here’s an example of using the modulus operator:
let x = 10;
let y = 3;
let z = x % y; // Modulus
In this example, z
will be equal to 1
, because 10
divided by 3
gives a remainder of 1
.
Increment and Decrement Operators
JavaScript also provides increment and decrement operators to add or subtract 1
from a variable.
The increment operator is represented by ++
, and the decrement operator is represented by --
. Here’s an example:
let x = 10;
x++; // x is now 11
x--; // x is now 10 again
These operators can be used either before or after the variable name, depending on whether you want to perform the operation before or after the variable is used in an expression.
Operator Precedence
When multiple arithmetic operators are used in a single expression, JavaScript follows a specific order of precedence to determine the order in which the operations should be performed. The order of precedence is as follows:
- Parentheses
()
- Increment and decrement operators
++
and--
- Multiplication and division operators
*
and/
- Modulus operator
%
- Addition and subtraction operators
+
and-
Arithmetic operations are fundamental to programming and are used in countless applications. In JavaScript, we have several built-in arithmetic operators for performing these operations, including addition, subtraction, multiplication, division, modulus, and increment/decrement. By understanding these operators and how to use them, you can create powerful programs that perform complex calculations and manipulate data.