Beginner Question about Loops

So I’ve made quite a bit of progress but I’m currently puzzled by something: loops.

TLDR at the bottom:

Relevant Link to the Exercise

Here’s what I understand from it all:

a) i is the equivalent of iterator.
b) the for loop is used to repeat a code.
c) the iterator expression appears in all three expressions that make up the for loop.
d) The start parts for the loop are: initialization, stopping condition and iteration statement.
e) Initialization: where the loop begins, the starting point if you will.

f) Stopping condition: when this condition is met, the loop will stop.

g) Iteration statement: that’s how the loop with make its modifications with lack of better words.

h) from what I can tell, there’s ++ and – so far for the iteration statement. I would imagine there are more but I haven’t learned them so far.

i) ++ and – mean add one and subtract one, respectively.

j) In the following example:
image
The loop will begin at 0 (initializer), then go up by 1 at a time (iteration statement) until it reaches a number lower than 4 (stopping condition).

k) console.log would record the result of this: 0, 1, 2 and 3.

l) We can loop through an array. That means to perform the looping operation on each element of the array.

m) In order to loop through an array, we need to use the .length property in its condition.

n) In the following example:
image
We’re dealing with an array index so I need to use [n] to identify which array I’m referring to. In other words, [0] is the bear, [1] the Sloth and [2] the Sea lion.

o) Here a loop is introduced followed by the usual brackets ( ). Then a variable is declare as being the iterator which is a bit more confusing as I didn’t realize I had to have a variable to use a loop. So now I’m feeling less solid but I carry on. Then I realize i here is just name of the variable so no need to fret about it. The next i that comes after is the stop condition.

p) So the initialization is at the string ‘Grizzly Bear’. Then it says animals.length and the increment is +1 because of ++.

TLDR: The .length sort of puzzles me.

Remember that arrays are zero-indexed, the index of the last element of an array is equivalent to the length of that array minus 1.

It seems like there’s on indication as for when the loop to stop in this case. Could someone explain?

The .length is a property of arrays. This property is an integer that is the number of elements in the array. This page gives more explanation of this property.

With the example given the following would output the number 3

console.log(animals.length);

You could then add another element to the array, say 'lion' and the output would then be the number 4.

Regarding the loop in the example: As you stated the variable i starts with the value 0 and increments by 1 for each iteration of the loop. This means that for the 'Sea Lion' element the value of i is 2. Then the value of i is increased to 3 and the condition is checked to determine if the loop will continue or exit. In this case the the value of animals.length is 3 and i is 3. The condition would evaluate to 3 < 3. This is false and the loop exits.

2 Likes

Hello,

The .length is a property of arrays. This property is an integer that is the number of elements in the array.
That’s clear.

You could then add another element to the array, say 'lion' and the output would then be the number 4.
So .length changes depending on how many arrays there are, so far so good.

As you stated the variable i starts with the value 0 and increments by 1 for each iteration of the loop.

Yes, I got that too.

So animals.length just means how many arrays there are in total. That’s what I couldn’t figure out as there were no numbers there. I would have thought i would have been: i < 3 would have made more sense.

i < 3 would work for this specific array. The advantage of using .length is that the same loop will work even if the array is changed (adding/removing elements).

This is where I’m at now.

And this is the code I’ve written so far:

// Write your code below
let bobsFollowers = ['Linda', 'Suzie', 'Beth', 'William']
let tinasFollowers = ['Linda', 'Suzie', 'Roger']
let mutualFollowers = []
for (let i )

and this is what I have to do now:
image
and this is the example they’ve given me:
image
So I did like they did for the first two variables except I used let instead of const but otherwise it’s similar.

It’s when I get to the last bit that I have more trouble. I know I need to use the method .push.

This is where I’m at now:

// Write your code below
let bobsFollowers = ['Linda', 'Suzie', 'Beth', 'William']
let tinasFollowers = ['Linda', 'Suzie', 'Roger']
let mutualFollowers = []
for (let i = 0; i < bobsFollowers.length; i++){
  for (let j = 0; j < tinasFollowers.length; j++){
    if (bobsfollowers[i] === tinasFollowers[j]){
      mutualFollowers.push[]
    }
  }
};     

I’d like a hint if possible, not the answer.

No; that should be until it reaches a number that is not lower than four. It continues while the number is lower than 4.

I think it is better to call those parentheses. Especially if you want terminology to be accurate.

The following for loop is the original type of for loop that was in the C language in the beginning:

for (let i=0; i<10; ++i)

I think that it could also be done using:

i=0;
while (i<10)
    ++i;

You might be using the term iterator in a non-typical manner. If you are talking about the for loop above then it should be called an index. Iterator typically refers to a variable that points to the item, without use of the variable in parentheses or brackets or whatever. If you don’t understand that then don’t fret it, just know that you can call it an index of subscript but iterator is something different.

I do not understand what you are referring to.

No, not arrays; array elements.

I am confused. I think they are telling you to do it in an inefficient manner. They are saying that for each element of an array, look at every element of another array. Well that would be necessary if both arrays are unsorted. In reality it would usually be more efficient to sort the items then match. For now we will do it the specified way.

First note that JavaScript is case-sensitive; bobsFollowers is not the same as bobsfollowers.

I think you need to use push(argument), not push. (If the square brackets look like a box then the forum software is altering what I have.)

Also, do you know how to use the debugger tools (such as F12) to debug JavaScript? Do you know how to single-step through the code to see waht is happening?

1 Like

No; that should be until it reaches a number that is not lower than four. It continues while the number is lower than 4.

Oh right ok. The loop will keep going for as long as it’s lower than 4. I misunderstood that.

I think it is better to call those parentheses . Especially if you want terminology to be accurate.

Ok, will do.

No, not arrays; array elements.

Right array elements.

First note that JavaScript is case-sensitive; bobsFollowers is not the same as bobsfollowers.

I can’t find any mistakes there but I’ll keep looking.

Also, do you know how to use the debugger tools (such as F12) to debug JavaScript? Do you know how to single-step through the code to see waht is happening?

No, but I’ll press F12 and see what happens.

I think you need to use push(argument), not push. (If the square brackets look like a box then the forum software is altering what I have.)

I thought .push was only used for array elements.

Yes, good point.

  • ( ) parenthesis: used to designate function parameters
  • [ ] brackets, or square brackets: to access an array index or object property
  • { } braces: contain a block of code
2 Likes

F12 works in all the major browsers and they have similar features but there are variances in the details. You can look at the HTML and see the console log and you can look at the scripts (JavaScript). There are many debugging tools, many of which are similar to what has existed for most languages for many years. You can find many articles and tutorials about the debugging tools.

Yes, we push a new element into the array. Your code was calling push but not specifying what to push. Also, push is a function so you need to use parentheses. But perhaps you do not want to use push; I am not sure what you are doing.

I tried F12 and it was overbearing to me. Lots of code I wasn’t familiar with.

Well .push would add an element at the end of an array/group of array elements.

I know I have to .push to mutualFollowers but for some reason I don’t know how to do it.

Another hint?

The main problem that I can see is that push[] is the wrong syntax. You need to use parenthesis instead to call the array’s push method. You also need to give the push method an argument, of what to push on to the end of the array.

      // mutualFollowers.push[];
      const follower = tinasFollowers[j];
      mutualFollowers.push(follower);
1 Like

If what you’re looking for is an intersection of both arrays (where only matching values of each array is retained) you can use more advanced techniques for that, such as the filter method.

const array3 = array1.filter(value => array2.includes(value));

Keep it basic, Paul, this is a CodeAcademy assignment after all :wink:

Also one slight clarification from the OP:

Actually, it’s when the condition is NOT met, the loop will stop. Your understanding is correct (as demonstrated in K) ), but your explanation isn’t.

Should actually be “The loop will begin at 0, then go up by 1 at a time, until it reaches a number that is not less than 4”. (Intuition: 0 is less than 4. If the stop condition was a truthy evaluator, the loop would terminate immediately.)

Or you could invert the statement and say it’s a Continuation Statement, which says “While this is true, continue.” (which is why most, if not all, for statements can be rewritten as while statements)

With Paul’s statement from post #12 (though it’s a little unnecessary to declare the variable independently of the array…), the code is complete and working. So this is where you should be thinking about the lesson and whether you’ve understood the concepts.

Oh, the poorly concealed advertisement message disappeared, didn’t have time to report it. A bit insulting really pretending to help so you can plug your merchandise, oh well.

I really appreciate your help.

Keep it basic, Paul, this is a CodeAcademy assignment after all

If you guys know other or better online courses/exercises (free or otherwise) I’d be interested. I like CodeAcadeymy so far though.I feel like the information is a bit condensed for my liking but otherwise it’s good. I’ve also used free code camp but it lacks funding a lot of things are incomplete which is a bit of a turn-off.

So code from #1 to #4 is ok then.

Just out of curiosity, I’m trying to learn to look at the debuggin window to find how where my errors are or give the hints that I’m looking for:
image
The arrow there seems to indicate there’s something wrong with the second ‘l’ of tinasFollowers but from what I can tell, it’s fine.
image
It’s spelled the exact same way as in the assignment. I’m wondering why it’s being pointed out as being problematic.

image
Why did they write bobsfollowers instead of bobsFollowers? I didn’t make a mistake in my casing.

So this is where you should be thinking about the lesson and whether you’ve understood the concepts.

I’d like to sum up the part of code which I find harder in my own words:
image

a) Declare the variable i which starts at the first array element then keep adding array elements for as long as the elements in i are one less than the array elements contained in bobsFollowers.

b) Do the same for variable declaration but for tinasFollowers this time and storing the variable in j.

c) then we get to the if statement namely:

  • If tinasFollowers and bobsFollowers share an array element, I need to push it somehow.

d) I decided to look at the solution. What matters if for me to understand the concepts anyway:
image
it’s the last mutualFollowers.push(bobsFollowers[i]); which I don’t understand.

Which is what I said, except I did not know how to get push[] to look right.

Which is what I said.

Perhaps they made a mistake or perhaps it was intentionally done wrong. The important thing is that it is easily overlooked and experience teaches to look for things like that. I think I did not notice until I ran the code using the debugger and the debugger said that bobsfollowers was not defined.

I would say declare the variable i initialized at the index of the first array element then increment the index for as long as the index in i is less than the number of array elements contained in bobsFollowers (the index of the last element).

I don’t know what you do not understand. What do you understand and what do you not understand? Do you understand the bobsFollowers[i] part? Or do you not understand the parentheses or why bobsFollowers[i] is in parentheses?

1 Like

a) Declare the variable i which starts at the first array element then keep adding array elements for as long as the elements in i are one less than the array elements contained in bobsFollowers

Keep correcting me on the syntax. It’s so vast and far-reaching that I need to consistently use the right terminology.

So like you said initialized because that’s the first step, where it starts. The index is the array identifier element number if you will.

In that case, why do you say:

increment the index

Shouldn’t you say, increment the array? The array elements are being added to arrays, not to the index. The index is just…
image
… that 'ant' is [0] while 'bison' is [1] etc…

I want to make sure we understand each other there before going further.

The comment was intended in the “Let’s help him learn to walk before running” sense :wink: CA is fine.

You’ll get more context from the first part of the error message - what KIND of error it was. Knowing where something occured is step 2. Knowing what went wrong comes first.

Are you sure about that? Look closer at your If statement in the picture immediately after you said that.

Not quite correct
i is just a number, counting from zero to length-1 (actually it technically counts to length).
You only add an array element if both arrays contain it; in mathematical terms, you are finding the intersection of the arrays.
You use the index to look up the value in the array. beasts[‘ant’] is meaningless to Javascript (in this context, anyway), but beasts[0] equals to “ant”. When i = 0, beasts[i] = “ant”.
You increment the index because you want to look at the next element in the array. You increment j in the same way, looped inside each other.

The following was explained in the previous post but I will add my explanation too.

You had the following code:

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

That you were describing in the following.

That is describing i, the index. That code does not change the array in any way. There are no elements in i. The index i is just a number.

Increment means change the value, typically by increasing by one. We are not changing the array; we are only changing the value used to access one element in the array.

I hope you learn C++ soon. It will help you to understand the peculiarities of JavaScript. JavaScript does some things differently that make things confusing. JavaScript is sometimes more flexible and when it is it is less precise.

1 Like

You’ll get more context from the first part of the error message - what KIND of error it was. Knowing where something occured is step 2. Knowing what went wrong comes first.

Ok, I’ll post a full screenshot next time or copy/paste the message.

Are you sure about that? Look closer at your If statement in the picture immediately after you said that.

etiennezizka:

Oh my god, you were right! I could’ve sworn I checked numerous times! It’s as if I couldn’t see anything after a while!!! At line 7, I made a mistake. It’s good to know the console is working as it should.
image

You use the index to look up the value in the array. beasts[‘ant’] is meaningless to Javascript (in this context, anyway), but beasts[0] equals to “ant”. When i = 0, beasts[i] = “ant”.
You increment the index because you want to look at the next element in the array. You increment j in the same way, looped inside each other.

Not sure about that part.

I hope you learn C++ soon. It will help you to understand the peculiarities of JavaScript. JavaScript does some things differently that make things confusing. JavaScript is sometimes more flexible and when it is it is less precise.

JavaScript is my first attempt at programming ever. I’ve never touched anything else. There are lessons on C++ on CodeCadamy but what I need is JavaScript to modify code in something I’m creating. I might have jumped into something more advanced from the get-go which is why I find the level of entry to be rather high.

The following is a description of arrays in the C language. I won’t be specific other than to describe arrays in a manner that helps to understand arrays in JavaScript.

In the C language all elements are the same type, such as integer or character. So an array a such as {55, 38, 9, 473} might be an array of integers. Each integer would usually occupy four bytes (depending on the machine and/or compiler). So if the array is at memory address 1000 then it might look the following in memory.

|Address|Value|
|1000     |55     |
|1004     |38     |
|1008     |9       |
|1012     |473   |

In C, when we access an array element, the compiler generates machine language that multiplies the index times the size of the elements and adds that to the base address of the array. So for a[2] it would multiply 2 (the index) times the element size (4) to get 8 then add that to the base address 1000 to get 1008. So a[2] is at machine address 1008.

JavaScript is more flexible and therefore less precise. In JavaScript indexes (the equivalent of indexes) can be a string and array elements in JavaScript can be any type; strings and numbers can be combined in arrays.

1 Like