dwyl / learn-javascript

A Series of Simple Steps in JavaScript :-)
Other
64 stars 15 forks source link

Understanding for loops #23

Open Cleop opened 7 years ago

Cleop commented 7 years ago

@sophielevens asked me this question about understanding for loops. The question is from Free Code Camp.

Question If you have a multi-dimensional array, you can use the same logic as the prior waypoint to loop through both the array and any sub-arrays. Here is an example:

var arr = [
  [1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) {
  for (var j=0; j < arr[i].length; j++) {
    console.log(arr[i][j]);
  }
}

This outputs each sub-element in arr one at a time. Note that for the inner loop, we are checking the .length of arr[i], since arr[i] is itself an array. Instructions Modify function multiplyAll so that it multiplies the product variable by each number in the sub-arrays of arrand the answer is this

function multiplyAll(arr) {
var product = 1;
// Only change code below this line
for (var i=0; i < arr.length; i++) {
for (var j=0; j < arr[i].length; j++) {
product *= arr[i][j];
}
}
// Only change code above this line
return product;
}
// Modify values below to test your code
multiplyAll([[1,2],[3,4],[5,6,7]]);

Her questions were:

  1. Where on earth did [i] and [j] come from? Have googled it and can't find out what they mean
  2. Also, (i++) is apparently the same as (i = i + 1) why do we want to add 1 to i?
Cleop commented 7 years ago

This was my response:

for (var i=0; i < arr.length; i++){...enter code here} is a for loop.

What a for loop does is: It says 'for every item in this array do (insert action here)'. So inside the brackets is where you're telling the for loop how to count/ how many times to repeat what it is going to do.

Let's break it down: The name of i doesn't mean anything, you can change this name to anything. However it's common practice to use i. What it represents is a counter for every item in the array. You need it so that the for loop knows how many times to do what you're telling it to do.

So when you say var i = 0, you're saying start the counter at 0 (because to start it somewhere higher wouldn't be very logical)

Then when you say i < arr.length, you're saying repeat the action whilst i (the counter) is less than the length of the array (which signifies how many items we need to loop through).

You might wonder, why do we loop through until i is less than the length of the array? Surely we should repeat the loop exactly as many times as there are items in the array?

The reason why it's only whilst i is less than arr.length is because our counter is starting at 0 and so the first time for executes, the counter is 1 behind and so the total needs to be 1 less than the total.

Then the final bit i++ is saying, make the counter increase by 1 each time you run the loop.

So in short you're saying, start a counter that will repeat a function a given number of times. Start the counter at 0, count and repeat the action until you've done it for each item in the array and every time the counter counts make sure you're just increasing it by 1 (not any other amount).

Where you see j, j again represents the counter but has been chosen as another random letter. You can't use i again because it's already been used and so if you used i twice one i would change the other i and it would break things. So to make sure things work they've chosen j instead. It's common to choose the next letter in the alphabet because it makes it easier to remember which loop is the first or outer loop and which one came next. You could use the word counter if you preferred it's just that people tend to use a letter like i because it's less to write and therefore once you're familiar with for loops it makes it faster/easier to read.

sophielevens commented 7 years ago

@Cleop Thank you so much for explaining this so well! I now completely get it and I will be able to sleep tonight 👍

footios commented 5 years ago

Hey there I've found a very interesting for loop Maybe you want to explain this one too.

It's for sorting an array of numbers. I like this line particularly: for (var j = 0; j < i; j++) link

var Arr = [1, 7, 2, 8, 3, 4, 5, 0, 9];

for (var i = 1; i < Arr.length; i++)
    for (var j = 0; j < i; j++)
        if (Arr[i] < Arr[j]) {
          var x = Arr[i];
          Arr[i] = Arr[j];
          Arr[j] = x;
        }

console.log(Arr);