We use cookies to enhance your experience on the site
CodeWorlds

Arithmetic and Assignment Operators

In Jurassic Park, correct calculations are crucial for safety - from calculating drug dosages for dinosaurs to determining resource requirements. JavaScript offers a set of operators that allow performing various mathematical operations and assignments.

Arithmetic Operators

In Dr. Wu's genetic laboratory, mathematical operations are essential for calculating DNA sequences and predicting dinosaur growth. Similarly, in JavaScript we have arithmetic operators for performing basic mathematical operations:

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 days
20
21// Remainder (modulo) (%)
22let eggCount = 17;
23let incubatorCapacity = 4;
24let eggsRemainingAfterFillingIncubators = eggCount % incubatorCapacity; // 1
25
26// Increment (++) - increase by 1
27let parkVisitors = 120;
28parkVisitors++; // now parkVisitors = 121
29
30// Decrement (--) - decrease by 1
31let threatLevel = 5;
32threatLevel--; // now threatLevel = 4
33
34// Exponentiation (**)
35let initialPopulation = 2;
36let breedingYears = 3;
37let estimatedPopulation = initialPopulation ** breedingYears; // 2^3 = 8

Order of Operations

Just like in mathematics, JavaScript respects the order of operations. If Dr. Wu needs to calculate how many kilograms of meat are needed for all carnivorous dinosaurs, he must follow the proper order:

1let smallCarnivores = 5;
2let largeCarnivores = 3;
3let dailyConsumptionSmall = 50; // kg
4let dailyConsumptionLarge = 300; // kg
5
6// Incorrect calculation (no parentheses)
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)

Standard order of operations (PEMDAS):

  1. Parentheses - (...)
  2. Exponents - **
  3. Multiplication and division - * /
  4. Addition and subtraction - + -

Assignment Operators

When updating resource levels or dinosaur populations in Jurassic Park, we use assignment operations. Similarly, JavaScript offers various assignment operators that combine an arithmetic operation with assignment:

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)
11
12// Multiplication assignment (*=)
13let dilophosaurPopulation = 4;
14dilophosaurPopulation *= 2; // equivalent to dilophosaurPopulation = dilophosaurPopulation * 2; (now 8)
15
16// Division assignment (/=)
17let foodRation = 1200;
18foodRation /= 4; // equivalent to foodRation = foodRation / 4; (now 300)
19
20// Remainder assignment (%=)
21let jeepSeats = 20;
22jeepSeats %= 6; // equivalent to jeepSeats = jeepSeats % 6; (now 2)
23
24// Exponentiation assignment (**=)
25let populationGrowth = 2;
26populationGrowth **= 3; // equivalent to populationGrowth = populationGrowth ** 3; (now 8)

Combining Arithmetic and Assignment Operators

Managing resources in Jurassic Park often requires complex calculations. In practice, we frequently combine different operations:

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 available rooms
9availableRooms -= newDinosaurs; // 45
10
11// Calculate new occupancy level (in percent)
12let occupancyLevel = (occupiedRooms + newDinosaurs) / (occupiedRooms + availableRooms) * 100;
13console.log(`Park occupancy level: ${occupancyLevel}%`); // 43.75%
14
15// Calculate additional staff needed (1 caretaker per 3 dinosaurs)
16let requiredStaff = Math.ceil((occupiedRooms + newDinosaurs) / 3);
17let additionalStaff = requiredStaff - careStaff;
18
19if (additionalStaff > 0) {
20  console.log(`We need to hire ${additionalStaff} additional caretakers.`);
21} else {
22  console.log("We have sufficient staff.");
23}

Note on Types and Conversion

Just like in real calculations in Jurassic Park, where we use different units (kilograms of food, liters of water, number of specimens), in JavaScript we need to pay attention to data types during operations:

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)

Summary

Arithmetic and assignment operators in JavaScript, just like calculations in Jurassic Park, are the foundation for more complex operations. They allow you to:

  • Perform basic mathematical operations (+, -, *, /, %, **)
  • Increment and decrement values (++, --)
  • Efficiently update variable values (+=, -=, *=, /=, %=, **=)

Remember about the order of operations and data types when performing operations - one miscalculation can lead to unforeseen situations, both in code and in a park full of predatory dinosaurs!

In the next lesson, we will look at comparison and logical operators, which are key to making decisions - both by the Jurassic Park security system and by our JavaScript programs.

Go to CodeWorlds