Loops
Use this article as a reference sheet for JavaScript loops.
- For loops —
for
loops execute a block of code for a set number of iterations. - While loops —
while
loops execute a block of code and continue as long as a certain condition is met.
For Loops
Loops are used to execute a block of code repeatedly, given a set of conditions. A for
loop will run the same block of code given a set number of iterations. Also, because JavaScript is a zero-indexed language the iteration usually starts at 0.
The syntax looks like this:
for (let i = 0; i < 3; i++) {console.log(`This is iteration ${i}`);}
The for
loop in the example above will output the following to the console:
This is iteration 0This is iteration 1This is iteration 2
Let’s break the example above into four parts:
- Within the
for
loop’s parentheses, the start condition islet i = 0
, which means the loop starts counting at0
. - The stop condition is
i < 3
, which means the loop runs as long asi
is less than3
. Wheni
is equal to3
, the loop will stop. - The iterator is
i++
. This means thati
increases by one after each loop —i++
is equivalent to writingi = i + 1;
. - Finally, the code block inside the curly braces executes until the loop stops.
The iterator variable (in this case i
) is always set to a numerical starting condition (let i = 0
). The first loop i
will equal 0
, the second loop i
will equal 1
, and the third loop i
will equal 2
. The variable i
is incremented by 1 after each loop is executed. It’s helpful to think that loops iterate by counting.
One application of for
loops is to iteratively access items in an array. We can do this by writing a for
loop and replacing the hard-coded number with the variable i
, like this: myArray[i]
.
const condiments = ['Ketchup', 'Mustard', 'Sauerkraut'];for (let i = 0; i < condiments.length; i++) {console.log(`Condiment: ${condiments[i]}`);}
In the example above, the length of the condiments
array (condiments.length
) is used to set the stop condition — length
can be used to access the number of items in any array. The loop executes for i
values of 0, 1, and 2. Each iteration, the condiment at the current index is logged to the console:
Condiment: KetchupCondiment: MustardCondiment: Sauerkraut
While Loops
for
loops are great, but they have a limitation: you must know the number of times you want the loop to run.
What if you want a loop to run an unknown or variable number of times?
For example, what if we had a deck of cards and wanted to flip cards until we drew a Spade? We aren’t able to predict the number of cards that will need to be flipped before encountering a spade. However, we do know the condition that necessitates continuing to draw cards: if the current card is not a spade, draw another card.
That’s the purpose of the while loop. A code block will continue to execute until a condition is no longer true.
let count = 5;while (count < 10){console.log(`The count is: ${count}`);count++;}
Let’s break down the example above:
- The
count
variable is set to5
. - The loop begins with the keyword
while
. - The condition inside the parentheses is
count < 10
. This means the code inside the while loop will continue to execute as long ascount
is less than10
. - Inside the code block, the value of
count
is logged to the console. The value ofcount
is then incremented by 1, using the increment operator (++
). The increment operator increases the value of a numeric variable by one. - When the value of
count
reaches10
, the condition inside the parentheses will no longer be true, and the while loop will stop executing.
Output:
The count is: 5The count is: 6The count is: 7The count is: 8The count is: 9
What would happen if count
were not incremented by one within each loop? The value of count
would remain equal to five, and the while
loop would continue to run forever. This is called an infinite loop. Infinite loops are a common cause of programs crashing.
Always review your while
loops to ensure that each iteration is getting closer to meeting the condition.
Author
'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'
Meet the full teamRelated articles
- Article
What is a for Loop in C++?
Learn how to use the `for` loop in C++ to iterate over sequences or ranges, explore its syntax and flow, and discover everyday use cases with practical examples highlighting its versatility and efficiency. - Article
JavaScript Glossary
Programming reference for JavaScript.
Learn more on Codecademy
- Skill path
Code Foundations
Start your programming journey with an introduction to the world of code and basic concepts.Includes 5 CoursesWith CertificateBeginner Friendly4 hours - Career path
Full-Stack Engineer
A full-stack engineer can get a project done from start to finish, back-end to front-end.Includes 51 CoursesWith Professional CertificationBeginner Friendly150 hours