Hello @dizzyshop
Welcome to
Glitch!
There is multiple ways you can loop through content, the first one, and probably the easiest one is called a for of loop, which is as simple as the following:
const numbers = [ 1, 2, 3, 4, 5, 6, 7 ];
for (let n of numbers)
{
console.log(n);
}
Firstly an array (numbers
) is created, containing a bunch of numbers. Secondly, a for look is defined with a statement saying that let n
is equal to each one of numbers
. This is also a so-called iteration loop.
The second way of doing looping through an array is by using the array’s boundaries (their length). It goes like this:
const names = [ "Christy", "Verdell", "Chaya", "Geneva", "Chadwick" ];
for (let index = 0; i < names.length; i++)
{
const value = names[index];
console.log(value);
}
In the above example, a list of names is defined. The example used a loop that defines three statements.
for ( statement1; statement2; statement3 )
{ ... }
Whereas statement1
executes only once before looping, statement2
which defines the condition executing the code block, and statement3
which is executed (every time) the code block has been executed.
There are however other ways to loop through an array to display or change information of what’s inside it. For instance array.map()
, which changes the contents of the elements stored inside the array. An example of this could be to make an array that shows who first came through the finish line.
// This is an ordered array of the names who crossed the finish line.
const finishList = [
"John",
"Jane",
"Bob",
"Alice"
];
// We'll iterate over the list using Array.map()
// and change the values to show the following:
// ${name} crossed the line and was the ${index} to cross.
const list = finishList.map(
(value, index) => `${value} crossed the line and`
+ `was the ${index} to cross.`
);
// Now to make things a little bit easier for ourselves,
// we'll use Array.join() to make it all into a string
// with the new values on a separate line.
const str = list.join("\n");
console.log(str);
// John crossed the line andwas the 0 to cross.
// Jane crossed the line andwas the 1 to cross.
// Bob crossed the line andwas the 2 to cross.
// Alice crossed the line andwas the 3 to cross.