Help. Loops and Arrays II


#1

var names =["Eric", "Tara", "Bill", "Sookie", "Jason"];

for (var i=0; i console.log("I know someone called" + names[i]);
}

what am i doing wrong?
there is no space between the name and the sentence given. can someone give me a hint?


#2

your for loop is all sorts of crazy. You are missing an entire section lets take a look.

var names = ["Eric", "Tara", "Bill", "Sookie", "Jason"];

for (var i=0; i console.log("I know someone called" + names[i]);
}

first lets go over how a for loop is constructed:

for(i = 0 ;///the starting point/// i ><= x; ///When to stop/// i +- ///what to do to i///) { 
    ///some code that does something here like console.log()///;
}

Your current code looks more like an "if" statement than a "for" loop An example of a for loop for an array would be:

var food = ["Pizza", "Pasta", "Wings", "Cheesecake"];
for (i = 0; i < food.length; i++) {
    console.log("I like to eat" + " " + food[i]);
}

So lets break this down. We have the array with lots of different foods in them no problem there.
Now into the for loop. The first part says "i = 0" we are telling the code that "i" is going to start off at "0".

Now it moves to the middle part which is "i < food.length" which basically says that as long as "i" is less than the length of "food" run the code below.

The code below is "console.log( "I like to eat" + " " + food[i])" the first part we know. The middle part is me adding a space between the sentence and the last bit. The last bit say to print the item in "food" that is equal to "i" In this case "i" is still "0" so it will print the first item in "food".

Now the program goes back top the 'for" loop and looks at the last bit which says "i++" Which is the same as saying "i + 1".

From here the program loops back to the first part of the "for" loop where, now, "i =1" then it checks the middle part to make sure that "i" is NOT greater than or equal to the length of "food" and will continue to run from there.

Your "for" loop had a beginning but no middle or end which is why you were getting errors.

Hope this helped and feel free to ask if you need things explained a bit more.