JavaScript Loops – Looping Backwards & Loops in Loops

Notes taken from The Complete JavaScript Course 2023: From Zero to Expert! course on Udemy.

Why would you use a for loop?

I asked Chat GPT this very question, and got this answer:

In JavaScript, a “for” loop is a control flow statement that allows you to execute a block of code a certain number of times. The “for” loop includes initialization, a condition, and incrementation/decrementation.

Here are some reasons and scenarios for using a “for” loop:

  1. Iterating over arrays: You might use a “for” loop when you need to iterate over an array of elements. Each loop iteration corresponds to one element in the array, so you can do something with each individual item.
    Example:
    let arr = [1, 2, 3, 4, 5]; for (let i = 0; i < arr.length; i++) { console.log(arr[i]); // prints each element of the array }
  2. Repetitive tasks: You would use a “for” loop when you need to perform a task a certain number of times. The “for” loop is a straightforward way to repeat a task.

    Example:
    for (let i = 0; i < 10; i++) { console.log(i); // prints numbers 0 to 9 }
  3. Traversing strings: Similar to arrays, you can use a “for” loop to traverse each character in a string.

    Example:
    let str = "Hello, World!"; for (let i = 0; i < str.length; i++) { console.log(str[i]); // prints each character in the string }
  4. Nested loops: You can use “for” loops inside other “for” loops when dealing with multi-dimensional data, such as a matrix or 2D array.
    Example:
    let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; for (let i = 0; i < matrix.length; i++) { for (let j = 0; j < matrix[i].length; j++) { console.log(matrix[i][j]);
    // prints each element in the matrix } }

Please note that while “for” loops are a classic control flow mechanism, there are other methods in JavaScript for similar use-cases, especially for arrays. This includes methods like Array.prototype.forEach, Array.prototype.map, Array.prototype.filter, and others, which might provide cleaner and more readable code in some scenarios. However, understanding the workings of a “for” loop is fundamental for programming in JavaScript and many other languages.

What are for loops?

Loops, by default, start at the beginning of an array, and work forwards, from variable/element 0 to element 10 – if an array has 10 elements.

Loops can also start at the end, say element 10 and work back to the first element.

for (let i = arrayname.length - 1; i>=0; i--)

In the code above.
The counter called “i” will keep running along as the variable/element is greater than or equal to 0 (the variable number, as in it’s order starting from 0)

Every time the loop runs, instead of adding 1 to “i”, subtract 1.

To print the current element to the console.log, the code should be:

for (let i = arrayname.length - 1; i>=0; i--) {
console.log(jonas[i]);
}

This image from kodify.net explains the parts of a standard for loop quite nicely

for loop

Loop inside a Loop

Loops within loops, are sometimes called “nested loops”.

Image Source

With a nested loop, the outer loop executes first, and the inner loop executes each time the outer loop executes.

If condition 1 is true, then condition 2 will execute.

For a much better explanation, please visit the educba.com website here.

Oh, one more thing that might be useful, I asked Chat GPT to explain for loops like I’m 10 years old:

“Imagine you have a big box of Lego blocks, and you want to look at each block one by one. You would start from the first block, then move to the second, then the third, and so on, until you’ve seen all the blocks. A “for” loop in JavaScript is like doing that – it’s a way for your computer to look at or do something with each item in a list, one at a time, from start to finish.

Here’s a real-life example:

Let’s say you’re on a website that shows all the movies currently playing in theaters. When the website wants to show you all the movie names, it might have a list (in programming, we call this an array) of all those movies. But how does it get from a list of movies to showing each one on your screen? It can use a “for” loop!

In the code of the website, it might look something like this:

let movies = ["Toy Story 4", "The Lion King", "Frozen 2", "Star Wars: The Rise of Skywalker"]; // This is the list of movies.

for (let i = 0; i < movies.length; i++) {
  console.log(movies[i]); // This will show each movie name, one after the other.
}

In this example, i is like a pointer that starts at the beginning of the list (0) and moves one step forward each time the loop runs (i++). The loop keeps going as long as i is less than the length of the list (i < movies.length). And in each loop, movies[i] is how we access each movie name.

This “for” loop helps the website to go through every movie in the list and do something with it – like showing it on your screen!”

JavaScript – the for Loop [2023] for beginners/dummies/SEO-helmets

A for loop, is a loop that will loop through (go through) the elements in an array or the properties of an Object.

You can use it to update arrays, count the number of elements etc

Loops can execute a block of code several times.

With arrays, it’s common(ish) to run the same code over with a different value.

Image source

screenshot source

For Loops tend to be used with arrays (I think!)

The code below the array in the screenshot below, starting with “for”, loops through the variable called “names” above it.
Once it loops through it create “name” and then “console.log(name);” will get it to print on the console.log screen

  • console.log just provides a way of testing and outputting stuff using web developer tools, inspect element etc.

The code below, will do the same as above, but this time it will add “Hello there” before each of the names:

You can also add if conditions. For example, in the code below, the loop will check if “Maria” is in the list, and if so, will print out “Maria is in my list”

You can get the loop to stop once it finds “Maria” by using the “break” keyword.

The above code will print “Ed, John and then Maria and “Maria is in my list”. It will then stop and it won’t print all the names up to “Potter”.

As well as using the for loop with arrays, you can also use it with a single variable like “age”, and add an incremented – for example “age++”

The code shown below will print out and loop 10 times. starting at 0, and then 1, 2 etc. until finally the condition age <10 is no longer met

When the age is 10, it will stop.

A web dev example

Get all the links on a page, and return the number of the links on the page.

When the loop gets to the 6th link, it is no longer less than links.length, and so the loop stops:

(you can click the image to see a lager version, the important code is :

for (i = 0; i < links.length; i++)

To print out the final link, change “<links.length” to “<= links.length” – meaning “less than or equal to links.length”

for (i = 0; i <= links.length; i++)

For In Loops

For in loops, are the same as for loops except they are shorter to write but less flexible.

For Loop Example with an Array

Work out the age of people, given an array with their year of birth in it.

start with the array and then a new array, which will hold the ages:

const years = [1991, 2007, 1969, 2020]
const ages = [];

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

ages.push (2023 – years [i] );

}

console.log(ages);

the “ages.push” code, will psh the results into the ages array

Continue & Break Statements

Continue is to exit the current iteration and move to the next one

Break will exit completely.

You can use with an if statement

continue loop statement

If the type of the current element, is not a string, then continue.

This will skip any elements/values that are not strings. Continue will exit the current iteration and not print to the console.log

Using break, will terminate the loop completely.

break loop statement