Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Loops in JavaScript

Uploaded by

dany.developper
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Loops in JavaScript

Uploaded by

dany.developper
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Loops in JavaScript

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/
Building_blocks/Looping_code

Loops are all about doing the same thing over and over again.

Often, the code will be slightly different each time round the loop, or
the same code will run but with different variables.

If we didn't use loops, we'd have to repeat the same code over and
over each time we wanted to implement it.

This would get very boring and difficult to maintain.

Most of the time when you use a loop, you will have a collection of
items and want to do something with every item.

The for...of loop

The basic tool for looping through a collection is the for...of loop:

Example:

const cats = ["Leopard", "Serval", "Jaguar", "Tiger",


"Caracal", "Lion"];
for (const cat of cats) {
console.log(cat);
}

In this example, for (const cat of cats) says:

Given the collection cats, get the first item in the collection.

Assign it to the variable cat and then run the code between the curly
braces {}.

Get the next item, and repeat (2) until you've reached the end of the
collection.

More specialized loops for collections

map()

Use to do something to each item in a collection and create a new


collection containing the changed items.

Example:

function toUpper(string) {
return string.toUpperCase();
}

const cats = ["Leopard", "Serval", "Jaguar", "Tiger",


"Caracal", "Lion"];

const upperCats = cats.map(toUpper);

console.log(upperCats);
// [ "LEOPARD", "SERVAL", "JAGUAR", "TIGER", "CARACAL",
"LION" ]

Here we pass a function into cats.map(),

and map() calls the function once for each item in the array, passing
in the item.

It then adds the return value from each function call to a new array,

and finally returns the new array.

In this case the function we provide converts the item to uppercase,

so the resulting array contains all our cats in uppercase.

[ "LEOPARD", "SERVAL", "JAGUAR", "TIGER", "CARACAL",


"LION" ]
filter()

Use to test each item in a collection, and create a new collection


containing only items that match.

Example:

function lCat(cat) {
return cat.startsWith("L");
}

const cats = ["Leopard", "Serval", "Jaguar", "Tiger",


"Caracal", "Lion"];

const filtered = cats.filter(lCat);

console.log(filtered);
// [ "Leopard", "Lion" ]

This looks a lot like map(),

except the function we pass in returns a boolean:


● if it returns true, then the item is included in the new array.

Our function tests that the item starts with the letter "L",

so the result is an array containing only cats whose names start with
"L":
[ "Leopard", "Lion" ]

Both are used with function expressions:

Note that map() and filter() are both often used with function
expressions.

Using function expressions we could rewrite the example above to be


much more compact:

const cats = ["Leopard", "Serval", "Jaguar", "Tiger",


"Caracal", "Lion"];

const filtered = cats.filter((cat) =>


cat.startsWith("L"));

console.log(filtered);
// [ "Leopard", "Lion" ]

The standard for loop

Not used for a collection of items but use when you want to run the
same code x amount of times.
for (initializer; condition; final-expression) {
// code to run
}

The keyword for, followed by some parentheses.

Inside the parentheses we have three items, separated by


semicolons:

An initializer
● usually a variable set to a number,
● which is incremented to count the number of times the loop has
run.
● It is also sometimes referred to as a counter variable.

A condition
● defines when the loop should stop looping.
● This is generally an expression featuring a comparison operator,
a test to see if the exit condition has been met.

A final-expression
● always evaluated (or run) each time the loop has gone through a
full iteration.
● It usually serves to increment (or in some cases decrement) the
counter variable, to bring it closer to the point where the
condition is no longer true.

Some curly braces that contain a block of code — this code will be run
each time the loop iterates.
Example:

function calculate() {
for (let i = 1; i < 10; i++) {
const newResult = `${i} x ${i} = ${i * i}`;
results.textContent += `${newResult}\n`;
}
results.textContent += "\nFinished!";
}

This code calculates squares for the numbers from 1 to 9, and writes
out the result. The core of the code is the for loop that performs the
calculation.

Let's break down the for (let i = 1; i < 10; i++) line into
its three pieces:
let i = 1: the counter variable, i, starts at 1.

Note that we have to use let for the counter, because we're
reassigning it each time we go round the loop.

i < 10: keep going round the loop for as long as i is smaller than
10.

i++: add one to i each time round the loop.

Inside the loop, we calculate the square of the current value of i, that
is:
● i * i.
● We create a string expressing the calculation we made and the
result
● and add this string to the output text.
● We also add \n, so the next string we add will begin on a new
line.

So:

During the first run, i = 1, so we will add 1 x 1 = 1.

During the second run, i = 2, so we will add 2 x 2 = 4.

And so on…
● When i becomes equal to 10 we will stop running the loop
● and move straight to the next bit of code below the loop, printing
out the Finished! message on a new line.
Example Simplified:

Use for loop for collections


for...of (Recommended)

const cats = ["Leopard", "Serval", "Jaguar", "Tiger",


"Caracal", "Lion"];

for (const cat of cats) {


console.log(cat);
}

Re-Writing with a for loop:

const cats = ["Leopard", "Serval", "Jaguar", "Tiger",


"Caracal", "Lion"];

for (let i = 0; i < cats.length; i++) {


console.log(cats[i]);
}

● In this loop we're starting i at 0,


● and stopping when i reaches the length of the array.
● Then inside the loop, we're using i to access each item in the
array in turn.

This works just fine, and in early versions of JavaScript, for...of


didn't exist, so this was the standard way to iterate through an array.
However, it offers more chances to introduce bugs into your code.

For example:
● you might start i at 1, forgetting that the first array index is zero,
not 1.
● you might stop at i <= cats.length, forgetting that the last
array index is at length - 1.

For reasons like this, it's usually best to use for...of if you can.

Example looping use case:

Log a message listing our cats

With for…of loop:

const cats = ["Pete", "Biggles", "Jasmine"];

let myFavoriteCats = "My cats are called ";

for (const cat of cats) {


myFavoriteCats += `${cat}, `;
}

console.log(myFavoriteCats); // "My cats are called


Pete, Biggles, Jasmine, "

The final output isn't well-formed:

My cats are called Pete, Biggles, Jasmine,


The format looks better like this:

My cats are called Pete, Biggles, and Jasmine.

Use for loop

We need to know when we are on the final loop iteration, and to


do that we can use a for loop and examine the value of i

const cats = ["Pete", "Biggles", "Jasmine"];

let myFavoriteCats = "My cats are called ";

for (let i = 0; i < cats.length; i++) {


if (i === cats.length - 1) {
// We are at the end of the array
myFavoriteCats += `and ${cats[i]}.`;
} else {
myFavoriteCats += `${cats[i]}, `;
}
}

console.log(myFavoriteCats); // "My cats are called


Pete, Biggles, and Jasmine."
Exiting loops with break

Use the break statement to exit a loop before all the iterations have
been completed.

Similar to switch statements — when a case is met in a switch


statement that matches the input expression, the break statement
immediately exits the switch statement and moves on to the code
after it.

A break statement will immediately exit the loop and make the
browser move on to any code that follows it.
https://codepen.io/jt_1/pen/PoVqZPN
Skipping iterations with continue

The continue statement works similarly to break, but instead of


breaking out of the loop entirely, it skips to the next iteration of the
loop.

Example:

This example takes a number as an input, and returns only the


numbers that are squares of integers (whole numbers).
In this case, the input should be a number (num). The for loop is
given a counter starting at 1 (as we are not interested in 0 in this
case), an exit condition that says the loop will stop when the counter
becomes bigger than the input num, and an iterator that adds 1 to the
counter each time.

Inside the loop, we find the square root of each number using
Math.sqrt(i), then check whether the square root is an integer by
testing whether it is the same as itself when it has been rounded down
to the nearest integer (this is what Math.floor() does to the number it
is passed).

If the square root and the rounded down square root do not equal one
another (!==), it means that the square root is not an integer, so we
are not interested in it. In such a case, we use the continue
statement to skip on to the next loop iteration without recording the
number anywhere.

If the square root is an integer, we skip past the if block entirely, so


the continue statement is not executed; instead, we concatenate the
current i value plus a space at the end of the paragraph content.

while and do...while loops

While loop

initializer
while (condition) {
// code to run

final-expression
}
This works in a very similar way to the for loop, except that

● the initializer variable is set before the loop,


● and the final-expression is included inside the loop after the
code to run
○ rather than these two items being included inside the
parentheses.

● The condition is included inside the parentheses,


● which are preceded by the while keyword rather than for.

The same three items are still present,

and they are still defined in the same order as they are in the for loop.

This is because you must have an initializer defined before you can
check whether or not the condition is true.

The final-expression is then run after the code inside the loop has run
(an iteration has been completed),

which will only happen if the condition is still true.

Example:

const cats = ["Pete", "Biggles", "Jasmine"];

let myFavoriteCats = "My cats are called ";


let i = 0;

while (i < cats.length) {


if (i === cats.length - 1) {
myFavoriteCats += `and ${cats[i]}.`;
} else {
myFavoriteCats += `${cats[i]}, `;
}

i++;
}

console.log(myFavoriteCats); // "My cats are called


Pete, Biggles, and Jasmine."

https://codepen.io/jt_1/pen/YzBGKbP

Do While loop

initializer
do {
// code to run

final-expression
} while (condition)

In this case, the initializer again comes first, before the loop starts.
The keyword directly precedes the curly braces containing the code to
run and the final expression.

Difference - do…while vs while

The main difference between a do...while loop and a while loop


is that

● the code inside a do...while loop is always executed at least


once.

That's because the condition comes after the code inside the loop.

So we always run that code, then check to see if we need to run it


again.

In while and for loops, the check comes first, so the code might
never be executed.

Do while Example:

Rewrite of the cat listing example again to use a do...while loop:

const cats = ["Pete", "Biggles", "Jasmine"];

let myFavoriteCats = "My cats are called ";


let i = 0;

do {
if (i === cats.length - 1) {
myFavoriteCats += `and ${cats[i]}.`;
} else {
myFavoriteCats += `${cats[i]}, `;
}

i++;
} while (i < cats.length);

console.log(myFavoriteCats); // "My cats are called


Pete, Biggles, and Jasmine."

Warning:

Warning:

With while and do...while — as with all loops — you must make sure that
the initializer is incremented or, depending on the case, decremented, so
the condition eventually becomes false.

If not, the loop will go on forever, and either the browser will force it to
stop, or it will crash.

This is called an infinite loop.


Which loop to use?

for...of:

● If you're iterating through an array or some other object that


supports it, and don't need access to the index position of each
item, then for...of is the best choice.
● It's easier to read and there's less to go wrong.

for (const item of array) {


// code to run
}

● For other uses, for, while, and do...while loops are largely
interchangeable.
● They can all be used to solve the same problems, and which one
you use will largely depend on your personal preference — which
one you find easiest to remember or most intuitive.
● We would recommend for, at least to begin with, as it is
probably the easiest for remembering everything —
○ the initializer, condition, and final-expression all have to go
neatly into the parentheses, so it is easy to see where they
are and check that you aren't missing them.

for:

for (initializer; condition; final-expression) {


// code to run
}
while:

initializer
while (condition) {
// code to run

final-expression
}

do...while:

initializer
do {
// code to run

final-expression
} while (condition)

More Loops

There are other loop types/features too, which are useful in


advanced/specialized situations and beyond the scope of this article.
If you want to go further with your loop learning, read our advanced
Loops and iteration guide.

You might also like