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:
1// Addition (+)
2let raptorCount = 5;
3let newHatchlings = 3;
4let totalRaptors = raptorCount + newHatchlings; // 8
5
6// Subtraction (-)
7let totalDinosaurs = 57;
8let transferredDinosaurs = 12;
9let remainingDinosaurs = totalDinosaurs - transferredDinosaurs; // 45
10
11// Multiplication (*)
12let dailyFoodRequirement = 20; // kg per dinosaur
13let troodontCount = 7;
14let totalRequirement = dailyFoodRequirement * troodontCount; // 140 kg
15
16// Division (/)
17let meatSupply = 1500; // kg
18let dailyConsumption = 300; // kg
19let 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:
1// Remainder (modulo) (%)
2let eggCount = 17;
3let incubatorCapacity = 4;
4let eggsRemainingAfterFillingIncubators = eggCount % incubatorCapacity; // 1
5
6// Exponentiation (**)
7let initialPopulation = 2;
8let breedingYears = 3;
9let 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 --:
1// Increment (++) - increase by 1
2let parkVisitors = 120;
3parkVisitors++; // now parkVisitors = 121
4
5// Decrement (--) - decrease by 1
6let threatLevel = 5;
7threatLevel--; // 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:
1let a = 5;
2console.log(++a); // 6 - increments first, then returns
3let b = 5;
4console.log(b++); // 5 - returns the old value first, then increments
5console.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:
1let smallCarnivores = 5;
2let largeCarnivores = 3;
3let dailyConsumptionSmall = 50; // kg
4let dailyConsumptionLarge = 300; // kg
5
6// Incorrect calculation - a missing term
7let incorrectConsumption = smallCarnivores + largeCarnivores * dailyConsumptionLarge;
8console.log(incorrectConsumption); // 905 (incorrect result!)
9
10// Correct calculation (with parentheses)
11let correctConsumption = (smallCarnivores * dailyConsumptionSmall) + (largeCarnivores * dailyConsumptionLarge);
12console.log(correctConsumption); // 1150 kg (correct result)
13
14// Here the parentheses really change the result
15console.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:
1// Basic assignment (=)
2let tRexCount = 2;
3
4// Addition assignment (+=)
5let visitors = 100;
6visitors += 50; // equivalent to visitors = visitors + 50; (now 150)
7
8// Subtraction assignment (-=)
9let fuelReserves = 1000;
10fuelReserves -= 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:
1// Multiplication assignment (*=)
2let dilophosaurPopulation = 4;
3dilophosaurPopulation *= 2; // equivalent to dilophosaurPopulation = dilophosaurPopulation * 2; (now 8)
4
5// Division assignment (/=)
6let foodRation = 1200;
7foodRation /= 4; // equivalent to foodRation = foodRation / 4; (now 300)
8
9// Remainder assignment (%=)
10let jeepSeats = 20;
11jeepSeats %= 6; // equivalent to jeepSeats = jeepSeats % 6; (now 2)
12
13// Exponentiation assignment (**=)
14let populationGrowth = 2;
15populationGrowth **= 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):
1// Scenario: Updating park resources after new dinosaurs hatch
2
3let availableRooms = 50;
4let occupiedRooms = 30;
5let newDinosaurs = 5;
6let careStaff = 15;
7
8// Update rooms: the new dinosaurs take free places
9availableRooms -= newDinosaurs; // 45
10occupiedRooms += newDinosaurs; // 35
11
12// Calculate new occupancy level (in percent)
13let occupancyLevel = occupiedRooms / (occupiedRooms + availableRooms) * 100;
14console.log(`Park occupancy level: ${occupancyLevel}%`); // 43.75%
15
16// Calculate required staff (1 caretaker per 3 dinosaurs)
17let requiredStaff = Math.ceil(occupiedRooms / 3); // 12
18let additionalStaff = requiredStaff - careStaff;
19
20if (additionalStaff > 0) {
21 console.log(`We need to hire ${additionalStaff} additional caretakers.`);
22} else {
23 console.log("We have sufficient staff.");
24}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:
1// Watch out for string operations!
2let report = "Report #";
3let reportNumber = 42;
4let fullReport = report + reportNumber; // "Report #42" (string concatenation)
5
6// Difference between numeric operations and string concatenation
7let result1 = 5 + 10; // 15 (number)
8let result2 = "5" + "10"; // "510" (string)
9let result3 = "5" + 10; // "510" (string, 10 was converted to string)
10let 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
1// Arithmetic and assignment operators
2// Calculations in the Jurassic Park management system
3
4// === Arithmetic operators ===
5console.log("=== Arithmetic operators ===");
6
7let raptors = 8;
8let triceratops = 12;
9
10// Addition, subtraction, multiplication, division
11console.log("Sum:", raptors + triceratops); // 20
12console.log("Difference:", triceratops - raptors); // 4
13console.log("Product:", raptors * 3); // 24
14console.log("Quotient:", triceratops / 4); // 3
15
16// Remainder (modulo)
17console.log("Remainder 10 % 3:", 10 % 3); // 1
18
19// Exponentiation
20console.log("2 ** 10:", 2 ** 10); // 1024
21
22// === Increment and decrement ===
23console.log("\n=== Increment / Decrement ===");
24
25let population = 50;
26population++; // 51
27console.log("After ++:", population);
28population--; // 50
29console.log("After --:", population);
30
31// Difference pre vs post
32let a = 5;
33console.log("++a:", ++a); // 6 (first increments, then returns)
34let b = 5;
35console.log("b++:", b++); // 5 (first returns, then increments)
36console.log("b after b++:", b); // 6
37
38// === Assignment operators ===
39console.log("\n=== Assignment operators ===");
40
41let supplies = 1000;
42supplies += 200; // supplies = supplies + 200
43console.log("After += 200:", supplies);
44
45supplies -= 150; // supplies = supplies - 150
46console.log("After -= 150:", supplies);
47
48supplies *= 2; // supplies = supplies * 2
49console.log("After *= 2:", supplies);
50
51supplies /= 4; // supplies = supplies / 4
52console.log("After /= 4:", supplies);
53
54// Your task:
55// 1. Calculate total food requirement (dinosaurs * kg/day)
56// 2. Use assignment operators to update resource status
57Remember: 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.
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: