Chapter 3 - Loops (JavaScript)
Here's a JavaScript-flavoured version of the same concepts, with small JS examples for each idea.
while loops
A while loop repeats a block of code as long as its condition is true.
Example: print "Hello, world." five times.
let spam = 0;
while (spam < 5) {
console.log("Hello, world.");
spam = spam + 1;
}
An "annoying" while loop
You can keep asking for input until the user types exactly what you want.
Example: keep asking for "your name".
let name = "";
while (name !== "your name") {
console.log("Please type your name.");
name = prompt(">");
}
console.log("Thank you!");
Infinite loops and break
while (true) creates an infinite loop; break lets you exit early from inside the loop.
Example: same program using break.
while (true) {
console.log("Please type your name.");
const name = prompt(">");
if (name === "your name") {
break;
}
}
console.log("Thank you!");
continue in loops
continue skips the rest of the loop body and jumps back to the top to recheck the condition.
Example: only "Joe" is asked for a password.
while (true) {
console.log("Who are you?");
const name = prompt(">");
if (name !== "Joe") {
continue; // go back to start of loop
}
console.log("Hello, Joe. What is the password? (It is a fish.)");
const password = prompt(">");
if (password === "swordfish") {
break; // exit loop
}
}
console.log("Access granted.");
Truthy and falsy values, Boolean()
In conditions, 0, "", null, undefined, and NaN are falsy; almost everything else is truthy. This is similar to Python but with more falsy values.
Example: use truthiness directly.
let name = "";
while (!name) { // while name is empty
console.log("Enter your name:");
name = prompt(">");
}
console.log("How many guests will you have?");
const numOfGuests = Number(prompt(">"));
if (numOfGuests) { // means "if numOfGuests !== 0"
console.log("Be sure to have enough room for all your guests.");
}
console.log("Done");
You can test truthiness with Boolean():
Boolean(0) // false
Boolean(42) // true
Boolean("") // false
Boolean("Hi") // true
for loops
JavaScript's for loop uses an initializer, condition, and update expression instead of range().
Example: basic for loop.
console.log("Hello!");
for (let i = 0; i < 5; i++) {
console.log("On this iteration, i is set to " + i);
}
console.log("Goodbye!");
Summing a series with for
You can accumulate a running total inside a loop.
Example: sum 0 to 100.
let total = 0;
for (let num = 0; num <= 100; num++) {
total = total + num;
}
console.log(total); // 5050
while equivalent of a for loop
Anything done with for can be done with while, though it's more verbose.
Example: while version of the loop.
console.log("Hello!");
let i = 0;
while (i < 5) {
console.log("On this iteration, i is set to " + i);
i = i + 1;
}
console.log("Goodbye!");
for loop arguments: start, stop, step
JavaScript's for loop handles start, stop, and step directly in its three expressions, equivalent to Python's range(start, stop, step).
Examples:
for (let i = 12; i < 16; i++) { // 12, 13, 14, 15
console.log(i);
}
for (let i = 0; i < 10; i += 2) { // 0, 2, 4, 6, 8
console.log(i);
}
for (let i = 5; i >= 0; i--) { // 5, 4, 3, 2, 1, 0
console.log(i);
}
Importing modules
In Node.js, you import modules with require() or ES module import. JavaScript has no built-in random module; use Math.random() instead.
Example: random integers in a loop.
function randInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
for (let i = 0; i < 5; i++) {
console.log(randInt(1, 10)); // random int 1–10
}
You can import Node.js modules:
const fs = require("fs");
const path = require("path");
Ending a program early with process.exit()
In Node.js, process.exit() immediately terminates the program, even if you're inside a loop.
Example: loop until the user types exit.
while (true) {
console.log("Type exit to exit.");
const response = prompt(">");
if (response === "exit") {
process.exit();
}
console.log("You typed " + response + ".");
}
Short program: Guess the Number
This program uses Math.random(), a for loop, and break to let the user guess a secret number between 1 and 20, with up to 6 tries.
function randInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const secretNumber = randInt(1, 20);
console.log("I am thinking of a number between 1 and 20.");
let guess;
let guessesTaken;
for (guessesTaken = 1; guessesTaken <= 6; guessesTaken++) {
console.log("Take a guess.");
guess = Number(prompt(">"));
if (guess < secretNumber) {
console.log("Your guess is too low.");
} else if (guess > secretNumber) {
console.log("Your guess is too high.");
} else {
break; // correct guess
}
}
if (guess === secretNumber) {
console.log("Good job! You got it in " + guessesTaken + " guesses!");
} else {
console.log("Nope. The number was " + secretNumber);
}
Short program: Rock, Paper, Scissors
This game uses nested while loops, Math.random(), and conditionals to play repeated rounds and track wins, losses, and ties.
function randInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log("ROCK, PAPER, SCISSORS");
let wins = 0, losses = 0, ties = 0;
while (true) { // main game loop
console.log(`${wins} Wins, ${losses} Losses, ${ties} Ties`);
// player input loop
let playerMove;
while (true) {
console.log("Enter your move: (r)ock (p)aper (s)cissors or (q)uit");
playerMove = prompt(">");
if (playerMove === "q") {
process.exit();
}
if (["r", "p", "s"].includes(playerMove)) {
break;
}
console.log("Type one of r, p, s, or q.");
}
if (playerMove === "r") {
console.log("ROCK versus...");
} else if (playerMove === "p") {
console.log("PAPER versus...");
} else {
console.log("SCISSORS versus...");
}
const moveNumber = randInt(1, 3);
let computerMove;
if (moveNumber === 1) {
computerMove = "r";
console.log("ROCK");
} else if (moveNumber === 2) {
computerMove = "p";
console.log("PAPER");
} else {
computerMove = "s";
console.log("SCISSORS");
}
if (playerMove === computerMove) {
console.log("It is a tie!");
ties++;
} else if (
(playerMove === "r" && computerMove === "s") ||
(playerMove === "p" && computerMove === "r") ||
(playerMove === "s" && computerMove === "p")
) {
console.log("You win!");
wins++;
} else {
console.log("You lose!");
losses++;
}
}
Overall idea of the chapter
The chapter's core ideas are: use while for "loop while condition is true," for for "loop a fixed number of times," control loops with break/continue, and combine all of this to build small interactive games. JavaScript uses C-style for loops instead of range(), Math.random() instead of random.randint(), and process.exit() instead of sys.exit().