javascript

Arithmetic Operators (+, -, *, /, %, **)

Learn JavaScript arithmetic operators like addition, subtraction, multiplication, division, modulo, and exponentiation. Understand how they perform calculations with numbers.

10 min read 8 sections Tutorial
Share

Arithmetic operators are special symbols that help you do math with numbers in JavaScript. They let you add, subtract, multiply, and divide, just like on a calculator. You will learn how each operator works and how to use them to perform calculations in your code.

Arithmetic Operators (+, -, *, /, %, **)

Arithmetic Operators (+, -, *, /, %, **)

In JavaScript, arithmetic operators are used to perform mathematical calculations. These operators take numerical values, called operands, and return a single numerical result. Understanding them is fundamental for any program that needs to handle numbers, from simple counting to complex financial calculations.

What are Arithmetic Operators?

Arithmetic operators are symbols that tell JavaScript to perform a mathematical operation, like adding two numbers or multiplying them.

Basic Math

Perform common math operations like addition and subtraction with ease.

Number Manipulation

Change and combine numerical values to get new results in your code.

Precise Calculations

Handle order of operations correctly to ensure your math is always accurate.

Building Logic

Use math operations to build conditions and control how your programs work.

What Are Arithmetic Operators?

Getting Started

What Are Arithmetic Operators?

Arithmetic operators are like the math symbols you already know. They let you do things like add numbers together or find the difference between them. When you use them, JavaScript performs the calculation and gives you a new number as the answer. This is useful for tasks like calculating scores, prices, or distances.

javascript
1// Declare a variable called 'apples' and give it the number 5.
2let apples = 5;
3// Declare a variable called 'oranges' and give it the number 3.
4let oranges = 3;
5
6// Use the '+' operator to add 'apples' and 'oranges'.
7// The result (8) is stored in 'totalFruits'.
8let totalFruits = apples + oranges;
9console.log("Total fruits: ", totalFruits); // This will show: Total fruits: 8
10
11// Use the '-' operator to subtract 'oranges' from 'apples'.
12// The result (2) is stored in 'fruitDifference'.
13let fruitDifference = apples - oranges;
14console.log("Fruit difference: ", fruitDifference); // This will show: Fruit difference: 2

Watch Out for Strings!

Using the + operator with strings will join them together, not add them as numbers. Always make sure your values are numbers if you intend to do math. For example, "5" + 3 will give you "53", not 8.

Understanding Each Operator

Understanding Each Operator

Each arithmetic operator has a specific job. Besides addition and subtraction, you can also multiply, divide, find remainders, and calculate powers. Knowing what each symbol does helps you build more complex calculations. This is important for tasks like calculating sales tax, splitting a bill, or figuring out compound interest.

javascript
1// Set up two numbers to work with.
2let num1 = 10;
3let num2 = 3;
4
5// Addition operator (+): Adds two numbers.
6let sum = num1 + num2; // 10 + 3 = 13
7console.log("Sum: ", sum);
8
9// Subtraction operator (-): Subtracts the right number from the left.
10let difference = num1 - num2; // 10 - 3 = 7
11console.log("Difference: ", difference);
12
13// Multiplication operator (*): Multiplies two numbers.
14let product = num1 * num2; // 10 * 3 = 30
15console.log("Product: ", product);
16
17// Division operator (/): Divides the left number by the right.
18let quotient = num1 / num2; // 10 / 3 = 3.333...
19console.log("Quotient: ", quotient);
20
21// Modulo operator (%): Returns the remainder of a division.
22// 10 divided by 3 is 3 with a remainder of 1.
23let remainder = num1 % num2; // 10 % 3 = 1
24console.log("Remainder: ", remainder);
25
26// Exponentiation operator (**): Raises the left number to the power of the right.
27// 10 to the power of 3 (10 * 10 * 10) = 1000.
28let power = num1 ** num2; // 10 ** 3 = 1000
29console.log("Power: ", power);
✗ BadWrong (String Concatenation)
// The '+' operator treats "10" as a string.
let result = "10" + 5;
console.log(result); // Output: "105"
✓ GoodCorrect (Numeric Addition)
// Use Number() to convert the string to a number first.
let result = Number("10") + 5;
console.log(result); // Output: 15
// Or ensure both are numbers from the start.
let num = 10;
let otherNum = 5;
let sum = num + otherNum;
console.log(sum); // Output: 15

Order of Operations and Grouping

Order of Operations and Grouping

Just like in regular math, JavaScript follows an order for calculations. Multiplication and division happen before addition and subtraction. This is called 'operator precedence.' You can use parentheses () to change this order and make sure calculations happen exactly as you intend. This helps prevent unexpected results in your math.

No Parentheses (Default Order)
// JavaScript follows PEMDAS/BODMAS rules.
// Multiplication happens before addition.
let calculation1 = 5 + 2 * 3;
// First: 2 * 3 = 6
// Then: 5 + 6 = 11
console.log(calculation1); // Output: 11
VS
With Parentheses (Custom Order)
// Parentheses force the addition to happen first.
let calculation2 = (5 + 2) * 3;
// First: (5 + 2) = 7
// Then: 7 * 3 = 21
console.log(calculation2); // Output: 21

When to Use Parentheses

Always use parentheses () if you want to change the default order of operations, or if you just want to make your code clearer. Even if they're not strictly needed, they can help others (and future you!) understand the calculation better.

Real-World Examples: Calculating with JavaScript

Real-World Examples: Calculating with JavaScript

Arithmetic operators are used everywhere in web development. You might use them to calculate the total price of items in a shopping cart, determine how many days are left until an event, or even animate elements on a screen. Here are some common ways you'll use them in practical projects.

1

Calculate Total Price with Tax

Imagine you're building an online store. You need to calculate the final price of an item, including sales tax. This involves multiplication and addition.

javascript
1// Define the item price and tax rate.
2let itemPrice = 100;
3let taxRate = 0.08; // 8% tax
4
5// Calculate the tax amount.
6let taxAmount = itemPrice * taxRate;
7
8// Calculate the total price by adding the item price and tax amount.
9let totalPrice = itemPrice + taxAmount;
10
11console.log("Item Price:", itemPrice);
12console.log("Tax Amount:", taxAmount);
13console.log("Total Price:", totalPrice); // Output: Total Price: 108
2

Distribute Items Evenly

If you have a certain number of items and want to put them into groups, the modulo operator can tell you how many items are left over. This is useful for pagination or assigning tasks.

javascript
1// Total number of students.
2let totalStudents = 27;
3// Number of students per group.
4let studentsPerGroup = 5;
5
6// Calculate how many full groups can be made using division.
7let numberOfGroups = Math.floor(totalStudents / studentsPerGroup);
8
9// Calculate how many students are left over using the modulo operator.
10let remainingStudents = totalStudents % studentsPerGroup;
11
12console.log("Number of groups:", numberOfGroups); // Output: Number of groups: 5
13console.log("Remaining students:", remainingStudents); // Output: Remaining students: 2
3

Calculate Future Growth

The exponentiation operator is great for calculating things that grow exponentially, like compound interest or population growth over time.

javascript
1// Starting amount of money.
2let principal = 1000;
3// Annual interest rate (5%).
4let annualRate = 0.05;
5// Number of years.
6let years = 3;
7
8// Calculate the final amount using the compound interest formula:
9// P * (1 + R)^T
10let finalAmount = principal * (1 + annualRate) ** years;
11
12console.log("Initial amount:", principal);
13console.log("Final amount after 3 years:", finalAmount.toFixed(2)); // Output: Final amount after 3 years: 1157.63

Beware of Division by Zero and NaN

Dividing any number by 0 in JavaScript results in Infinity (or -Infinity). If you try to perform arithmetic operations on values that are not numbers (and cannot be converted), the result will often be NaN (Not a Number), which can break your calculations if not handled.

Arithmetic Operator Reference

Arithmetic Operator Reference

OperatorNameDescriptionExample
+AdditionAdds two numbers or concatenates strings.`5 + 3` results in `8`
-SubtractionSubtracts the right operand from the left operand.`10 - 4` results in `6`
*MultiplicationMultiplies two numbers.`6 * 2` results in `12`
/DivisionDivides the left operand by the right operand.`15 / 3` results in `5`
%ModuloReturns the remainder of a division.`10 % 3` results in `1`
**ExponentiationRaises the left operand to the power of the right operand.`2 ** 3` results in `8` (2*2*2)

Test Your Knowledge

Test Your Knowledge

Test Your Knowledge

Quick Check

What is the result of 7 + 3 * 2 in JavaScript?

Quick Check

Which operator returns the remainder of a division?

Quick Check

What will (10 - 2) * 3 evaluate to?

Quick Check

If x = 2 and y = 4, what is the value of x ** y?

Quick Reference

Quick Reference

Quick Reference

Pro Tips
  • 1Addition (+) — Used to sum two numbers or concatenate (join) strings. Be careful with mixed types.
  • 2Subtraction (-) — Finds the difference between two numbers. Can also make a number negative.
  • 3Multiplication (*) — Calculates the product of two numbers.
  • 4Division (/) — Divides one number by another. Can result in Infinity if dividing by zero.
  • 5Modulo (%) — Returns the remainder of a division. Useful for checking even/odd numbers.
  • 6Exponentiation (**) — Raises a number to a power. For example, 2 ** 3 is 2 to the power of 3 (8).
  • 7Operator Precedence — Operations like multiplication and division happen before addition and subtraction.
  • 8Parentheses () — Use these to control the order of operations and make your calculations clear.
  • 9Type Coercion — JavaScript can sometimes change data types automatically. Be aware of this, especially with the + operator.
  • 10NaN (Not a Number) — Results from invalid arithmetic operations, like trying to multiply a number by a non-numeric string.

Assignment Operators

Learn how to assign values to variables, often combined with arithmetic operations (e.g., +=, -=).

Comparison Operators

Discover how to compare values (e.g., ==, ===, <, >) to make decisions in your code.

Logical Operators

Understand && (AND), || (OR), and ! (NOT) to combine or invert boolean conditions.

Data Types

Deepen your knowledge of JavaScript's data types, especially numbers and strings, and how they interact.

You've Mastered Arithmetic!

Congratulations! You now understand the core arithmetic operators in JavaScript. You can perform basic math, control the order of operations, and apply these skills to solve real-world coding problems. Keep practicing to become a math wizard in your code!

Try it in the Javascript Compiler

Run and experiment with Javascript code right in your browser — no setup needed.

Continue Learning