In life we understand Loops to be a repetitive direction an object is traveling in perpetuity or until some condition forces the looping to stop.
Computers are actually quite well-suited to do repetitive tasks like looping and running sub-task during each iteration of the loop. So virtually every programming has a concept of looping built-in but may actually look a bit different in implementation and execution.
Javascript Loops
In Javascript, my current language of choice a loop can look like this.
for(let i = 0; i < array1.length; i++){
//statement
console.log(array1[i])
}
It can also make use of control statements like break or continue to control the flow of the loop.
break: This will break out of the loop on command
continue: This will continue the loop on command
Here are the four basic parts of a loop:
- Initialization: ex: let i = 0
This will serve as a counter for each element in the array.
Click here to learn more about arrays
- Condition: ex: i < array1.length
This condition is checked at each iteration of the loop and continues to a sub-task for each element unless the condition is false, A false condition will immediately stop the loop and produce a return value if given.
Here we are using the length of an array to check if each iteration is less than the array length with the array1.length method.
- Final-Expression: ex: i++
The final expression is generally an instruction to decrement or increment the initialized value until we meet our condition that causes the end of the loop.
- Statement: ex: console.log(array1[i])
The statement will consist of any sub-tasks you want to do with each element in the array. In this case, we are logging each element of the array to the console efficiently with the loop.
Types
Here are the different types of loops in Javascript:
for loop
const numbers = [ 2, 3, 7, 11]
let sum = 0
for (let i = 0; i < numbers.length; i++){
sum += numbers[i]
console.log(sum, i)
}
// => output:
2 0
5 1
12 2
23 3
while loop
const numbers = [ 2, 3, 7, 11]
let i = 0 // initialization happens here
while(i < 4){ // condition happens here
console.log(numbers[i], i)
i++ // final-expression happens here
}
// => output:
2 0
3 1
7 2
11 3
do..while loop
const numbers = [ 2, 3, 7, 11]
let i = 0
do {
if (numbers[i] % 2 === 0) {
console.log(numbers[i] + ' is even')
} else {
console.log(numbers[i] + ' is odd')
}
i++
} while (i < numbers.length)
// => output:
2 is even
3 is odd
7 is odd
11 is odd
Bonus: Also try to give these for..of & for..in loops a spin.
Let's chat about Loops
Hopefully, this helped you to learn a bit about loops or bring my understanding about how they work. If you enjoyed this post feel free to leave a comment about your thoughts and experiences working with loops in Javascript.
Happy Coding,
Terry Threatt
Top comments (0)