Control Structures
Table of Contents
Control structures are the fundamental building blocks of programming that determine the flow of execution in a program. Without them, a program would simply run in a single, straight line from start to finish. By using control structures, you can make your code dynamic, allowing it to make decisions, repeat tasks, and jump between different sections.
Iterations
Code Runner Challenge
For loop
View IPYNB Source
%%js
//CODE_RUNNER: For loop
// 1. Set the number you want to use here
let inputNumber = 5;
function calculateMath(n) {
let sum = 0;
// Loop 1: Adds numbers 1 through n
for (let i = 1; i <= n; i++) {
sum += i;
}
let product = 1;
// Loop: Multiplies numbers 1 through n
for (let j = 1; j <= n; j++) {
product = product * j;
}
// Console log the results
console.log("Results for the number: " + n);
console.log("The total sum is: " + sum);
console.log("The factorial is: " + product);
}
// 3. Run the function using the input number
calculateMath(inputNumber);
Lines: 1
Characters: 0
Output
Click "Run" in code control panel to see output ...
This code uses a for loop to keep multiplying the numbers from 1-n until it reaches n and also add number 1 - n. A for loops keep running for a specific amount of time or until its if finished proccessing a sequence.
Code Runner Challenge
while and for each
View IPYNB Source
%%js
//CODE_RUNNER: while and for each
// A list of game items
const inventory = ["Sword", "Shield", "Potion"];
// 1. FOR EACH: Used to do something to every item in a list
console.log("Checking inventory...");
inventory.forEach(item => {
console.log(`- You have a ${item}`);
});
// 2. WHILE: Used to repeat until a specific condition is met
let health = 100;
let poisonLevel = 3;
console.log("\nYou are poisoned!");
while (health > 85) {
health -= poisonLevel; // Subtract 3 health each iteration
console.log(`Health dropping... Current Health: ${health}`);
}
console.log("Safe! The poison wore off.");
Lines: 1
Characters: 0
Output
Click "Run" in code control panel to see output ...
The while loop keeps repeating the code as long as a certain condition is being fufilled (In this case it is the players health.) The for each loop is used to do a certain action to every item in a list (In the example it procceses the players inventory.)
Conditionals
In JavaScript, conditionals are used to make decisions in your code. They allow the program to perform different actions based on whether a specific condition is true or false.
}
//Collision detection
// Checking if the player hits the ground boundary
if (player.y + player.height >= ground.y) {
player.y = ground.y - player.height; // Stop them from falling
player.isGrounded = true; // Update their status
} else {
player.isGrounded = false; // They are in mid-air
}
// State changes
if (gameState === "MENU") {
drawStartMenu();
} else if (gameState === "PLAYING") {
updateGameWorld();
} else if (gameState === "GAMEOVER") {
drawGameOverScreen();
}
Collision detection uses conditionals to constantly check if the coordinates of two game objects overlap, such as a player’s boundary hitting a wall. If the mathematical condition is true, the code inside the if statement executes to stop movement or decrease health, directly linking physical interaction to logical checks.
State transitions rely on conditionals to manage the high-level flow of the game, like switching from a “Start Menu” to the “Active Gameplay” screen. By checking a status variable within an if/else if chain, the program can decide which set of logic and graphics to render at any given moment based on the player’s progress.
Nested Conditionals
Nested conditionals are if statements placed inside other if statements. They are used when a game needs to check a secondary condition only after a primary condition has already been met.
Code Runner Challenge
Nested Conditionals
View IPYNB Source
%%js
// CODE_RUNNER: Nested Conditionals
for (let num = 1; num <= 50; num++) {
if (num % 5 === 0) {
if (num % 25 === 0) {
if (num % 50 === 0) {
console.log(num + " is divisible by 50, 25, 5, and 1");
} else {
console.log(num + " is divisible by 25, 5, and 1");
}
} else if (num % 10 === 0) {
console.log(num + " is divisible by 10, 5, 2, and 1");
} else {
console.log(num + " is divisible by 5 and 1");
}
} else if (num % 2 === 0) {
console.log(num + " is divisible by 2 and 1");
} else {
console.log(num + " is only divisible by 1");
}
}
Lines: 1
Characters: 0
Output
Click "Run" in code control panel to see output ...
In this code, nested conditionals act as a layered filtering system that only evaluates specific, deeper conditions after a broader “parent” condition has been satisfied. By placing checks for multiples of 25 and 50 inside the initial check for multiples of 5, the program creates a logical hierarchy that narrows down the identity of a number step-by-step.