for loops in 4 steps
A for loop is similar to a do or a while loop but much more compact. Typically used for actions that need to be run a particular amount of times. Also useful when working with arrays.
You should know at least a little bit about other loops in javascript before diving in given their many similarities.
Building a simple for loop…
- Basic for loop structure
2. Add in variable. Usually displayed as a single letter given it is just a place counter. This will initialize the loop by defining a variable.
3.Create a condition that checks to continue. As long as the value stored in i is < 10, the loop will run. As soon as value is 11, the loop is finished.
4.Finally you want to make sure the loop ends at some point by updating the state of the loop. Change the value of i each time through the loop.
A while loop turned into a for loop..
Here’s an example of how while and for loops are related.
While Loop..
Now lets get loopy, we’ll recreate this while loop as a for loop..
You can see how it is easy to create the same loop with less lines of code. Also, while we’re on the subject. Looper was a great movie.
//This is a barebones explanation and for loops can become very, very complex
//Newbie so if you have any additional insights, comment and I’ll update.