Caution to reader: this blog post is 3 months or older. Blog posts older than three months may contain details about the Hack Reactor program that are no longer accurate. Please refer to other pages on our website to confirm current information and email us with questions.
What is the difference between a for loop and a while loop? And what about the for-in, do-while and for-each?
For Loops: When you know how many times you want to loop. When you are iterating through the indices of an array. When you have some sort of counter.
For-In Loops: When you are iterating over the properties of an object.
For-Each: When you want to iterate over the values of an object's properties.
While Loops: When you may be unsure of the number of times to loop.
When you want to loop while some condition is true.
Do-While Loops: When you want it to loop at least once before checking if the condition is true.
Can you think of any good rules of thumb for when to use these loops? Watch these videos about for loops and while loops below!
Intro to While Loops: Transcription
For those who don't know what a loop is, let me explain. As programmers, we're really lazy. We like to work smarter, not harder. What a loop does is it allows us to run code as many times as we want, repeatedly, without having to type that line of code in every time.
Let's say I wanted to write something out on the screen ten times. I could go ahead and be boring and type out document.write and type in whatever, like "this is a sentence" or something.
I could copy and paste it ten times and that would be fine. It would run. But that's not very efficient. I've wasted ten lines of code in my text editor.