Arithmetic Operators: Performing Calculations
Why This Matters: Arithmetic operators are the backbone of numerical computations in JavaScript. From simple calculations to complex algorithms, mastering these operators is essential for handling any kind of quantitative data in your programs.
Operators are special symbols or keywords that JavaScript provides to perform operations on values and variables. Arithmetic operators are used to perform common mathematical calculations like addition, subtraction, multiplication, and division. They work with numbers (and sometimes strings or booleans, due to type coercion).
Let's explore the primary arithmetic operators in JavaScript.
1. Addition (+)
The addition operator performs mathematical addition between two numbers.
Important Note: If one of the operands is a string, the + operator performs string concatenation instead of mathematical addition (due to type coercion).
Examples:
2. Subtraction (-)
The subtraction operator performs mathematical subtraction.
Examples:
3. Multiplication (*)
The multiplication operator performs mathematical multiplication.
Examples:
4. Division (/)
The division operator performs mathematical division. The result can be a floating-point number even if both operands are integers.
Special Cases:
- Dividing by zero with a non-zero number results in
Infinityor-Infinity. - Dividing zero by zero results in
NaN(Not a Number).
Examples:
5. Modulo (Remainder) (%)
The modulo operator returns the remainder of a division operation. It's often used to check if a number is even or odd, or to wrap numbers around a specific range.
Examples:
6. Exponentiation (**)
The exponentiation operator raises the first operand to the power of the second operand. It was introduced in ES2016.
Syntax: base ** exponent
Alternative: Math.pow(base, exponent)
Examples:
7. Increment (++) and Decrement (--)
These operators are used to increase or decrease a variable's value by 1. They are unary operators (work on a single operand).
Important Distinction: Prefix vs. Postfix
- Postfix (
variable++orvariable--): - Returns the original value of the variable. - Then, increments/decrements the variable. - This means if you use it in an expression, the expression uses the old value.
- Prefix (
++variableor--variable): - First, increments/decrements the variable. - Then, returns the new value of the variable. - This means if you use it in an expression, the expression uses the new value.
Recommendation: For clarity, especially when learning, it's often safer to use variable = variable + 1; or variable += 1; (which we'll cover in assignment operators) instead of ++ or -- when the order of operation is critical or might be misunderstood. Use ++ or -- primarily when you just want to increment/decrement a variable on its own line.
Exercise: Operator Playground
In the editor below, perform the following calculations and log each result to the console:

