JavaScript and TypeScript course · Module 1: JavaScript Basics
Arithmetic and Assignment Operators
In this lesson9
The morning briefing in the Jurassic Park control center starts with numbers. How much meat should the raptors get? How many eggs will not fit in the incubators? How many visitors have come through the gate? Dr. Rex hands these calculations to the park systems, and JavaScript gives them two families of tools: arithmetic operators, which calculate, and assignment operators, which store the result in a variable.
The Four Basic Operations
Addition, subtraction, multiplication and division are written with +, -, * and /, and JavaScript calculates just like a calculator in the lab:
// Addition (+)
let raptorCount = 5;
let newHatchlings = 3;
let totalRaptors = raptorCount + newHatchlings; // 8
// Subtraction (-)
let totalDinosaurs = 57;
let transferredDinosaurs = 12;
let remainingDinosaurs = totalDinosaurs - transferredDinosaurs; // 45
// Multiplication (*)
let dailyFoodRequirement = 20; // kg per dinosaur
let troodontCount = 7;
let totalRequirement = dailyFoodRequirement * troodontCount; // 140 kg
// Division (/)
let meatSupply = 1500; // kg
let dailyConsumption = 300; // kg
let daysOfSupply = meatSupply / dailyConsumption; // 5 daysNotice what these operations do not do: raptorCount and totalDinosaurs keep their values, and the result goes into a new variable. Division does not cut off fractions either: 7 / 2 gives 3.5, because integers and fractions share a single number type in JavaScript.
Remainder and Exponentiation
The % operator returns the remainder of a division: 17 eggs at 4 per incubator means four full incubators and one egg waiting in line. The ** operator raises a number to a power:
// Remainder (modulo) (%)
let eggCount = 17;
let incubatorCapacity = 4;
let eggsRemainingAfterFillingIncubators = eggCount % incubatorCapacity; // 1
// Exponentiation (**)
let initialPopulation = 2;
let breedingYears = 3;
let estimatedPopulation = initialPopulation ** breedingYears; // 2^3 = 8Despite the % sign, this operator has nothing to do with percentages: 10 % 3 is 1, because 10 = 3 · 3 + 1. And 2 ** 3 means 2 · 2 · 2, which is 8, not 6 or 9.
Increment and Decrement
Counters often change by one: a visitor walks in, an alert drops by a level. For that, JavaScript has the shortcuts ++ and --:
// Increment (++) - increase by 1
let parkVisitors = 120;
parkVisitors++; // now parkVisitors = 121
// Decrement (--) - decrease by 1
let threatLevel = 5;
threatLevel--; // now threatLevel = 4Unlike + and -, these operators change the variable itself, so on a const they end with a TypeError. They also come in two forms that differ in the value returned at the moment of use:
let a = 5;
console.log(++a); // 6 - increments first, then returns
let b = 5;
console.log(b++); // 5 - returns the old value first, then increments
console.log(b); // 6Both variables end up at 6; the only difference is what reaches console.log on that same line. My advice: write ++ on its own line, not in the middle of a bigger expression.
Order of Operations
Dr. Rex is calculating the daily needs of the carnivores: five small predators eat 50 kg each, three large ones 300 kg each. Here is an intern's attempt and the fix:
let smallCarnivores = 5;
let largeCarnivores = 3;
let dailyConsumptionSmall = 50; // kg
let dailyConsumptionLarge = 300; // kg
// Incorrect calculation - a missing term
let incorrectConsumption = smallCarnivores + largeCarnivores * dailyConsumptionLarge;
console.log(incorrectConsumption); // 905 (incorrect result!)
// Correct calculation (with parentheses)
let correctConsumption = (smallCarnivores * dailyConsumptionSmall) + (largeCarnivores * dailyConsumptionLarge);
console.log(correctConsumption); // 1150 kg (correct result)
// Here the parentheses really change the result
console.log((smallCarnivores + largeCarnivores) * dailyConsumptionLarge); // 2400Where does 905 come from? Multiplication goes first, so JavaScript computes 3 * 300 and adds 5, which is just the number of animals. The mistake is in the formula, not in the order of operations. In the correct version the parentheses are there for readability, because without them the result would still be 1150. They only change the result in the last line, where they force the animals to be added first.
Standard order of operations (PEMDAS):
- Parentheses -
( ) - Exponents -
** - Multiplication and division -
*/ - Addition and subtraction -
+-
The acronym comes from the names of the levels: Parentheses, Exponents, Multiplication/Division, Addition/Subtraction. The % operator sits on the same level as * and /, and operations on the same level run from left to right. The exception is exponentiation, evaluated from the right: 2 ** 3 ** 2 is 512. You will see the full table in the lesson on operator precedence.
Assignment Operators
Counters are rarely set from scratch; they are updated. Instead of writing visitors = visitors + 50, you can combine the operation with the assignment in a single operator:
// Basic assignment (=)
let tRexCount = 2;
// Addition assignment (+=)
let visitors = 100;
visitors += 50; // equivalent to visitors = visitors + 50; (now 150)
// Subtraction assignment (-=)
let fuelReserves = 1000;
fuelReserves -= 250; // equivalent to fuelReserves = fuelReserves - 250; (now 750)Writing count += 5 means exactly the same as count = count + 5: read the value, add 5 and store the result in the same variable. The remaining operators work the same way:
// Multiplication assignment (*=)
let dilophosaurPopulation = 4;
dilophosaurPopulation *= 2; // equivalent to dilophosaurPopulation = dilophosaurPopulation * 2; (now 8)
// Division assignment (/=)
let foodRation = 1200;
foodRation /= 4; // equivalent to foodRation = foodRation / 4; (now 300)
// Remainder assignment (%=)
let jeepSeats = 20;
jeepSeats %= 6; // equivalent to jeepSeats = jeepSeats % 6; (now 2)
// Exponentiation assignment (**=)
let populationGrowth = 2;
populationGrowth **= 3; // equivalent to populationGrowth = populationGrowth ** 3; (now 8)A compound operator overwrites the variable, so just like ++ it will not work on a const. I recommend it over the long form: the variable name appears once, so you cannot make a typo while writing it a second time.
Combining Operators in Practice
Real tasks combine several operators. After five young dinosaurs hatch, the hatchery rooms need updating, the occupancy must be calculated and we need to check whether there are enough caretakers (one per three dinosaurs):
// Scenario: Updating park resources after new dinosaurs hatch
let availableRooms = 50;
let occupiedRooms = 30;
let newDinosaurs = 5;
let careStaff = 15;
// Update rooms: the new dinosaurs take free places
availableRooms -= newDinosaurs; // 45
occupiedRooms += newDinosaurs; // 35
// Calculate new occupancy level (in percent)
let occupancyLevel = occupiedRooms / (occupiedRooms + availableRooms) * 100;
console.log(`Park occupancy level: ${occupancyLevel}%`); // 43.75%
// Calculate required staff (1 caretaker per 3 dinosaurs)
let requiredStaff = Math.ceil(occupiedRooms / 3); // 12
let additionalStaff = requiredStaff - careStaff;
if (additionalStaff > 0) {
console.log(`We need to hire ${additionalStaff} additional caretakers.`);
} else {
console.log("We have sufficient staff.");
}We update both variables, because the hatchlings take free rooms while the total stays the same: 80. Math.ceil rounds up, since you cannot hire two thirds of a caretaker: 35 / 3 means 12 people. We have 15, so the program prints the second message. The text in backticks with ${...} is a template literal, and if picks one of two paths. We will cover both tools in upcoming lessons.
Watch Out for Text
The + operator has a double nature: when at least one side is text, it joins strings instead of adding. This is the concatenation from the lesson on type conversion:
// Watch out for string operations!
let report = "Report #";
let reportNumber = 42;
let fullReport = report + reportNumber; // "Report #42" (string concatenation)
// Difference between numeric operations and string concatenation
let result1 = 5 + 10; // 15 (number)
let result2 = "5" + "10"; // "510" (string)
let result3 = "5" + 10; // "510" (string, 10 was converted to string)
let result4 = 5 + "10"; // "510" (string, 5 was converted to string)The other arithmetic operators convert text to a number, so "5" - 2 gives 3. That is why you should convert form data with Number() before adding it to a counter.
Summary
Arithmetic and assignment operators are the foundation of more complex operations. They let you:
- perform mathematical operations (
+,-,*,/,%,**), - increment and decrement values (
++,--), - update variables concisely (
+=,-=,*=,/=,%=,**=).
Mind the order of operations and the data types: a miscalculation can be dangerous in a park full of predators. In the next lesson you will meet comparison and logical operators, which let the park systems make decisions.
Practice
The sandbox holds the control center console: population sums, 10 % 3, 2 ** 10, a comparison of ++a with b++ and supply updates. Change the numbers and predict every result before it shows up in the console. At the end, two tasks are waiting for you to solve.
Code for this lesson: index.js
// Arithmetic and assignment operators
// Calculations in the Jurassic Park management system
// === Arithmetic operators ===
console.log("=== Arithmetic operators ===");
let raptors = 8;
let triceratops = 12;
// Addition, subtraction, multiplication, division
console.log("Sum:", raptors + triceratops); // 20
console.log("Difference:", triceratops - raptors); // 4
console.log("Product:", raptors * 3); // 24
console.log("Quotient:", triceratops / 4); // 3
// Remainder (modulo)
console.log("Remainder 10 % 3:", 10 % 3); // 1
// Exponentiation
console.log("2 ** 10:", 2 ** 10); // 1024
// === Increment and decrement ===
console.log("\n=== Increment / Decrement ===");
let population = 50;
population++; // 51
console.log("After ++:", population);
population--; // 50
console.log("After --:", population);
// Difference pre vs post
let a = 5;
console.log("++a:", ++a); // 6 (first increments, then returns)
let b = 5;
console.log("b++:", b++); // 5 (first returns, then increments)
console.log("b after b++:", b); // 6
// === Assignment operators ===
console.log("\n=== Assignment operators ===");
let supplies = 1000;
supplies += 200; // supplies = supplies + 200
console.log("After += 200:", supplies);
supplies -= 150; // supplies = supplies - 150
console.log("After -= 150:", supplies);
supplies *= 2; // supplies = supplies * 2
console.log("After *= 2:", supplies);
supplies /= 4; // supplies = supplies / 4
console.log("After /= 4:", supplies);
// Your task:
// 1. Calculate total food requirement (dinosaurs * kg/day)
// 2. Use assignment operators to update resource status
Remember: an arithmetic operator only calculates, while an assignment operator stores the result, like a lab assistant who first weighs a portion and only then writes it into the feeding log.
Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What is the result of the expression 10 % 3 in JavaScript?
2. What will the expression 2 ** 3 return in JavaScript?
3. What is equivalent to the notation: count += 5?
Hands-on tasks in the game
- Vertical ordering
Arrange arithmetic operators from highest to lowest precedence: