Short & Sweet Javascript- Loops
What is a loop?
A loop is an instruction that repeats until a condition is met. Loops are extremely useful. They are used when we want to perform an instruction on every iteration in our data. For example, if we need to increment all numbers in our dataset by two.
While Loops
A while loop, loops through a block of code as long as the condition is true.
The do/while loop is a while loop but it is slightly different. This loop will run the code block once before checking if the condition is true- then it will repeat the loop as long as the condition is true. This results in the loop always be executed at least once (even if the condition is false) because the code block is executed before the condition is tested.
For Loops
The for loop, loops through code for a specified number of times.
It is also possible to loop through the properties of an object by using a for/in loop. And by using a for/of loop we can loop through the values of an iterable object.
Summary
- Use while loops when the number of iterations is unknown
- Use for loops when the number of iterations is known
Happy coding ✌️