Lesson 13, Thursday, 2024-10-31
An array
is a container type that holds multiple values:
// we create an empty array using []
let emptyArray = [];
// we put the values we want in square brackets
// separated by commas
let ages = [19, 33, 25, 40];
let cities = ['London', 'Paris', 'Berlin'];
We can access elements in the array by number using square brackets "[]
"
The numbering starts at 0
(think floors of a building):
let books = ['Harry Potter', 'The Hobbit', 'Game of Thrones'];
console.log(books[0]); // "Harry Potter"
console.log(books[1]); // "The Hobbit"
Output your name to console.log
two times.
console.log('Alan');
console.log('Alan');
Output your name to console.log
14207 times.
// huh ????
We use loops to run the same code in our programs repeatedly.
More generally, a loop is a way to repeat an action multiple times as long as a certain condition is true
.
Let's say I want to bake a cake:
We take an empty bowl and keep our ingredients ready.
We need 5 cups of flour.
- What's the action that we need to repeat?
- For how long do we need to repeat it?
- The action we need to repeat is adding a cup of flour to the bowl
- We repeat it 5 times
We can distinguish different parts in a loop:
- initialization: a starting point
- condition: a test to see if the loop should stop
- update: changes the value checked by the condition
- action: what we want to repeat
- initialization: no flour in the bowl (
cupsOfFlour = 0
) - condition: did we put less than 5 cups of flour? (
cupsOfFlour < 5
) - update: cups of flour in the bowl (
cupsOfFlour++
) - action: add flour to the bowl
Let's see how to make an actual loop in JavaScript.
A while
loop repeats its body while its condition
is true
:
while (condition) {
// body is executed while "condition" is true
console.log('Hello from while loop');
}
let cupsOfFlour = 0; // initialization
while (cupsOfFlour < 5) { // condition
// action
console.log('Take a cup of flour and put it in the bowl');
// update
cupsOfFlour++;
console.log('There are now ' + cupsOfFlour + ' cups in the bowl');
}
A while loop might execute zero to unlimited times:
let isHungry = false; // we just ate
while (isHungry) {
eat(); // this is never reached!
}
Always make sure that a while
loop's condition is eventually set to false
.
Otherwise your loop will run infinitely.
let bitesOfChocolate = 0;
while (bitesOfChocolate < 10) {
console.log('Bites of chocolate: ' + bitesOfChocolate);
console.log('Still hungry.');
}
// this code will print "Bites of chocolate: 0" and
//"Still hungry" until your laptop runs out of battery,
// you close the browser, you reboot, or the universe ends
Let's console.log
the numbers from 1 to 5 using a while
loop.
Quiz: Let's console.log
the numbers from 1 to 5 using a while
loop.
let i = 1; // initialize i with 1
while (i <= 5) {
// repeat this loop until we reach 5
console.log(i);
i++; // update i at every step
}
What will this loop output?
let i = 0;
while (i < 2) {
console.log(i);
}
Answer: 0, until you run out of battery
- How many times will the loop run?
let i = 10;
while (i < 15) {
console.log(i);
i++;
}
Answer: 5 times
- Output your name five times
- Output the squares of the first 10 numbers starting with 1 (1, 4, 9, 16, ...)
Output your name five times
let i = 0;
while (i < 5) {
console.log('Carlo');
i++;
}
Squaring the first 10 numbers
let i = 1;
while (i < 11) {
console.log(i * i); // or i ** 2
i++;
}
- What can we do with loops?
- What are the main parts of a loop?
- Can a loop run 0 times?
- Can a loop run only 1 time?
- a loop lets us execute a block of code multiple times
- the block is executed as long as certain condition is true
- we normally need a starting point, initializing some variable
- inside the block that is repeated, we usually update some value to make sure that the loop can stop
But developers are lazy, we want to write the least amount of code as possible.
Hence, the for loop!
look at this example, can you explain how do we write a for loop?
for (let counter = 0; counter < 10; counter++){
console.log(counter);
}
A for
loop works like a while
loop, but it's more concise.
for (initialization; condition; update) {
// loop body
}
for
(
- initialization
;
- condition
;
- update
The 3 main parts of the loop are all in one line, separated by semicolons (;
).
Let's replace our while
loop with a for
:
let i = 1; // part 1 - *initialize* the counter
while (i < 6) { // part 2 - *test* the exit *condition*
console.log(i);// loop body
i++; // part 3 - *update* the counter
}
// same code with for loop:
for (let i = 1; i < 6; i++) {
console.log(i);
}
- A
while
loop executes its body while the condition istrue
. - A
for
loop first runs the initialization part, then tests the condition part and, if it istrue
, executes the body. After every loop, it executes the update part.
- We use a
for
loop if we know in advance how often it will be executed.
for (let i = 0; i < 1000; i++) {
console.log(i);
}
- We use a
while
loop if we don't know how many times the loop will be executed.
while (passwordIsWrong) {
askForPassword();
}
use a for loop and output the numbers between 0 and 10 (including both) to the console
for(let i = 0; i < 11; i++){
console.log(i);
}
use a for loop and output the numbers between 13 and 17 (including both) to the console
for(let i = 13; i <= 17; i++){
console.log(i);
}
For loops and arrays work wonderfully together!
let languages = ["english", "german", "arabic", "japanese"]
for (let i = 0; i < languages.length; i++){
console.log(languages[i]);
}
use a for loop to output: hello name
! for every one of your friends:
let friends = ['Abdo', 'Harald', 'Sevtap', 'Meli'];
// ????
use a for loop and output the numbers between 5 and -3 (including both) to the console
for(let i = 5; i > -4; i--){
console.log(i);
}
- Output the sum of the first 10 numbers (e.g. 1 + 2 + 3 + ...)
- Output a countdown from 10 to 0 to console (e.g. 10, 9, 8, ...)
- Bonus: Instead of zero, output "liftoff!"
- Bonus: Instead of counting down to console.log, write the output to a an HTML page