Loops in JavaScript
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.
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 basic tool for looping through a collection is the for...of loop:
Example:
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.
map()
Example:
function toUpper(string) {
return string.toUpperCase();
}
console.log(upperCats);
// [ "LEOPARD", "SERVAL", "JAGUAR", "TIGER", "CARACAL",
"LION" ]
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,
Example:
function lCat(cat) {
return cat.startsWith("L");
}
console.log(filtered);
// [ "Leopard", "Lion" ]
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" ]
Note that map() and filter() are both often used with function
expressions.
console.log(filtered);
// [ "Leopard", "Lion" ]
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
}
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.
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:
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:
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.
Use the break statement to exit a loop before all the iterations have
been completed.
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
Example:
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.
While loop
initializer
while (condition) {
// code to run
final-expression
}
This works in a very similar way to the for loop, except that
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),
Example:
i++;
}
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.
That's because the condition comes after the code inside the loop.
In while and for loops, the check comes first, so the code might
never be executed.
Do while Example:
do {
if (i === cats.length - 1) {
myFavoriteCats += `and ${cats[i]}.`;
} else {
myFavoriteCats += `${cats[i]}, `;
}
i++;
} while (i < cats.length);
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.
for...of:
● 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:
initializer
while (condition) {
// code to run
final-expression
}
do...while:
initializer
do {
// code to run
final-expression
} while (condition)
More Loops