Javascript Arithmetic Operators
In this lesson, we’ll explore arithmetic operators in JavaScript, covering essential math operations such as addition, subtraction, multiplication, division, modulus, and more. Arithmetic operators are the backbone of basic calculations in JavaScript and allow us to easily manipulate numbers and variables to perform math tasks. Let’s dive in!
1. Addition Operator `(+)`
The addition operator +
is used to add numbers together. This operator works with two numbers (operands), and when used, it combines their values.
Example 1: Adding Numbers Directly
console.log(100 + 20); // Output: 120
In this example, we added 100
and 20
, giving us a result of 120
.
Example 2: Adding Variables
let num1 = 100;
let num2 = 50;
console.log(num1 + num2); // Output: 150
Here, we stored values in num1
and num2
and added them together. This is helpful when using stored data for calculations.
2. Subtraction Operator `(-)`
The subtraction operator -
simply subtracts one number from another.
Example: Subtracting Two Numbers
Even if the values are stored as strings (like "100"
), JavaScript will treat them as numbers and still subtract them.
console.log(100 - 20); // Output: 80
console.log("200" - "50"); // Output: 150
Note: If you try to subtract text from a number, JavaScript returns NaN (Not a Number).
3. Multiplication Operator `(*)`
The multiplication operator *
multiplies two numbers together.
Example: Basic Multiplication
console.log(10 * 5); // Output: 50
console.log("5" * "2"); // Output: 10
4. Division Operator `(/)`
console.log(100 / 10); // Output: 10
5. Exponentiation Operator `**`
console.log(2 ** 4); // Output: 16
6. Modulus Operator `(%)`
Example: Modulus
console.log(20 % 10); // Output: 0
console.log(21 % 10); // Output: 1
let x = 8;
console.log(++x); // Output: 9
console.log(x++); // Output: 9 (but x is now 10)
- Pre-Increment
(++x)
:Increases the value before returning it. - Post-Increment (x++):Returns the value first, then increases it.
8. Decrement Operator `(--)`
The decrement operator --
works similarly but subtracts 1
from the variable’s value.
- 1Parentheses
()
: Always calculated first. - 2Exponentiation
**
: Next in line. - 3Multiplication
*
, Division/
, and Modulus%
: All have the same precedence and are calculated from left to right. - 4Addition
+
and Subtraction-
: Calculated last, also from left to right.
Example of Operator Precedence
Conclusion
Mastering JavaScript arithmetic operators allows you to handle calculations easily, from simple additions to complex expressions. Remember, JavaScript evaluates these operations left to right, respecting the precedence rules above. By using these operators, you can write cleaner, more effective code in your JavaScript projects.