Day 5 of 100 days of Code
Nkem
Posted on February 23, 2022
Today I learnt about loops.looping through a sequence and an array. A loop is a sequence of instruction that is continually repeated until a condition is reached.
• for loop
• while loop
• do while loop
The for loop has the following syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
for (let i = 0; i < 5; i += 1) {
console.log(i)
}
Statement 1 is the let i=0; is the initial vairable. It sets the initial number to be zero.
Statement 2 is the condition that is to be met, in this case i < 5. This means it should keep looping while i is less than 5.
Statement 3 is executed (every time) after the code block has been executed.
In this case it will output
0
1
2
3
4
The while loops loops through a code as long until the condition is met
while (condition) {
// code block to be executed
}
let i = 0
while ( i < 5) {
console.log(i)
i++
}
This does the same as the for loop example above.
Do while
This is a variant of the while. It instructs the program to execute a program while condition remains true.
do {
// code block to be executed
}
while (condition);
let i= 0
do {
console.log (i)
i++
while(i < 5)
}
Honestly for some untapped reasons I do not like this do/while loop.
Looping through an array
let messages = [
"Hey, how's it going?",
"I'm great, thank you! How about you?",
"All good. Been working on my portfolio lately.",
"Same here!",
"Great to hear"
]
for (let i = 0; i < messages.length; i += 1) {
console.log(messages[i])
}
Posted on February 23, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 25, 2024