For loops are a headache, help

nuff said

were ez in the beginning, now they haunt my shit

1 Like

What do you mean by they “were ez in the beginning”? Do you have a particular example of how For Loops can be a headache?

2 Likes

Do you have a question?

Learning to describe problems is an important part of learning how to code.

Also, the more information you give us, the more likely we are to be able to help.

2 Likes

how exactly do for loops look over arrays?
and what exactly am i supposed to put in the curly brackets after i write my for loop, normally i’d so if statements, but i’m still not entirely sure.

if you understand if statements , I think you will be able to understand the for loop as there are some conceptual similarities. essentially were are still writing conditions and then instructions . so for example, in your if statement you have a condition

 if( 2 > 1) {
console.log("true") }

2 is greater then one, so the condition is true and the instructions which are written in between the curly brackets are followed so "true " is printed out to the console.

i think it helpful to first think about a simple problem. lets say you have an arr

var numbers = [1,2,3,4,5]

and all you want to do is console.log each number in the array

if you want to do this for all the items in the array it would be helpful to know how many items are in the array, you can find out the length of the array by writing

console.log(numbers.length)

a for loop can help us solve the problem of printing out each numbers in the array. We want to write a condition that somehow says for all the items in the array, please follow some instructions.

To do this we first declare a variable which is why you often see at the beginning of the for loop something like

(var i = 0)

why i and why 0 ? It is convention to use i, but you could write something else . Why 0? this is because we want to follow some instructions for each item of the array and arrays are 0 indexed. This means the first item in the array has an index of 0 (not 1 like you might expect in normal life). so if you write

 console.log(numbers[0])

it will print out the first item of the array, which in our case is the number 1

So we want to start counting from 0 so var i = 0. Now we want to follow the instructions for each item in the array so this is where it would be useful to know how many items are in the array (numbers.length)

now in the for loop you will see a semi colon after the var i = 0 ;
and then a condition is written, so for looping over arrays you will usually see something like

i < numbers.length 

This is a condition. here we are saying, as long as the the value of i is less than numbers.length

Why do we want to only do the instructions when i is less than numbers.length ?

well arrays are 0 indexed which means in our example the first index is numbers[0]
which is 1, which might lead you to think the numbrs.length is 4 but this is not how it works. the length is 5.

.length counts the number of items in the array starting at 1.

so because there are 5 items, the length is 5. So if we want to do some instruction for each item in the array we can do the instructions for one number less than the length.

so we write the condition ( i < numbers.length) because this would be like writing i < 5 . you might still think here wait, but why less than 5? this is because remember the index of the first item in the array is index[0]. and var i starts at 0.

so if we count 0,1,2,3,4 we would have counted all the items in the array. so that is why we can write the condition ( i < numbers.length) ie i < 5.

now after you usually see i++ . This part is saying increase i by 1. This is because we want to do something for each item in the array and to do this we will need to increase the i by 1 each time the instructions in the curly braces are run which will now be explained.

now comes the curly braces { } of the for loop.

when the for loop runs it checks whether the condition is true, ie in this case - is var i = 0
less than numbers.length? yes it is because var i = 0 , and numbers.length = 5 so it then moves on to say do whatever is in the curly braces . In our case we wanted to console.log each numbers so we would write in the curly braces

console.log(numbers[i])

remember we set var i = 0 so this is like writing numbers[0] and as we mentioned arrays are 0 indexed so numbers[0] is the first item in our array, in our case that is number 1.

now we HAVE done everything in our curly braces. the for loop increases i by 1. why? this is because we told it to when we wrote i++. so now var i = 1, the for loop checks the condition, is 1 < numbers.length? yes it is because 1 < 5 so it goes back to the curly braces and follows the instructions. console.log(numbers[i]). now i = 1 and as we mentioned arrays are 0 indexed so numbers[1] is the second item in the array ie 2 so it prints 2 to the console. now i++ increases i again so now i = 2 , and it checks the condition again and then does what is in the curly braces.

it keeps doing this until the condition would not be met. as we mentioned. arrays are 0 indexed and we set var i = 0 at the beginning. the condition was while i < numbers.length.

numbers.length is 5 so everytime the loop runs we have in the curly braces console.log(numbers[i]) and i keeps changing from in the first case numbers[i] is numbers [0] which is the first item in the array ie number 1.

see below for how it changes.
numbers[0] = 1 ,numbers[1] = 2, numbers[2]=3, numbers[3,]= 4 numbers[4]=5

hopefully this clears it up a bit

6 Likes

In a for-loop, you can repeat a process. You first initialize a variable, then set a condition, while the condition is true, the loop keeps working, and then lastly you have an action which occurs on each iteration just after the condition has been evaluated to true(if it always evaluates to true, it may lead to harmful results, unless it’s intentional and you use the “break” keyword somewhere down the line).

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

In this loop, the value of i is incremented everytime the statement i < arr.length evaluates to true, and hence the value of i changes, and to iterate over an array, you can use the index [i] since the condition will evaluate to true as long as i is less than the length of the array, and on each iteration, the value of i changes, and hence arr[i] may refer to 1 on one iteration and 2 on another, and this way it’ll iterate through the whole sequence. I recommend you break it down and analyze it yourself.

1 Like

wow man thanks, this was very helpful, explained in to more detail what i wanted to know,
so much appreciated

thank you for explaining, this was helpful

1 Like

still a bit conflicted on what i can/can’t put in the curly braces

You can put whatever you want, assuming it is valid JS. The curly braces define a code block.

For an if statement, they aren’t always required:

// valid JS
if (conditon) doSomething();

// valid JS
if (conditon)
  doSomething();

// valid JS
if (conditon) {
  doSomething();
}

For an if statements if you only have one thing to do, you can leave off the curly braces. If you have more than one thing, you need the curly braces to have both be conditional:

if (conditon)
  doSomething1(); // only run if condition is met
  doSomething2(); // always run, indenting doesn't change that
if (conditon) {
  doSomething1(); // only run if condition is met
  doSomething2(); // only run if condition is met
}

So, if you don’t need to do more than one thing, you don’t need curly braces (a code block). Some people (like me) will always use curly braces with if statements, even if they aren’t needed. For me it’s a habit because my old company’s linter insisted on it.


For a for statement, the same rule applies:

// valid JS
for (let i = 0; i < 10; i++) doSomething();

// valid JS
for (let i = 0; i < 10; i++)
  doSomething();

// valid JS
for (let i = 0; i < 10; i++) {
  doSomething();
}

Just like the if statement, those all work fine if you only need to do 1 thing. If you need more than one thing done, then you need a code block. (OK, technically you could use comma operators, but that gets messy.)

for (let i = 0; i < 3; i++) console.log('hey', i);

// hey 0
// hey 1
// hey 2

for (let i = 0; i < 3; i++)
  console.log('hey', i);

// hey 0
// hey 1
// hey 2

for (let i = 0; i < 3; i++) {
  console.log('hey', i);
}

// hey 0
// hey 1
// hey 2

and

// without curly braces

for (let i = 0; i < 3; i++)
  console.log('hey', i);
  console.log('ribbit');

// hey 0
// hey 1
// hey 2
// ribbit


// with curly braces

for (let i = 0; i < 3; i++) {
  console.log('hey', i);
  console.log('ribbit');
}

// hey 0
// ribbit
// hey 1
// ribbit
// hey 2
// ribbit

I personally like this way of iterating through an array:

let myArray = ["this", "that", "the other", 1, 5, 6];

for (let element of myArray) {
    console.log(element);
}

I hope this will help you.

This is a great explanation . I am sure I ma not the only new to programing person who has benefited from it. Now, if you could write one like this for every topic, that would be awesome. :slight_smile:

1 Like

thanks, I appreciate you taking the time to leave that comment, glad it helped.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.