DEV Community

Nkem
Nkem

Posted on

Day 5 of 100 days of Code

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
}
Enter fullscreen mode Exit fullscreen mode
for (let i = 0; i < 5; i += 1) {
    console.log(i)
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

The while loops loops through a code as long until the condition is met

while (condition) {
  // code block to be executed
}
Enter fullscreen mode Exit fullscreen mode
let i = 0
while ( i < 5) {
console.log(i)
i++
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode
let i= 0
do {
console.log (i)
i++
while(i < 5)
}
Enter fullscreen mode Exit fullscreen mode

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])
}

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
xurgg profile image
xurgg

nice!