Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Introduction to Programming Objects and Arrays Arrays

Jeremy Dortch
Jeremy Dortch
3,799 Points

Repeating the 0 place in the array

var friends = ["Jake", "Jordan", "Will", "Jordi", "Jon"];
console.log(friends);
console.log(friends.length);

var friendNumber = 1;
console.log(friends[friendNumber]);

for(var i=0; i < friends.length; i+=1){
console.log(friends[i]);
}

For some reason it's spitting out the following:

Jordan Jake Jordan Will Jordi Jon

I don't know why it's replacing Jake with Jordan and repeating it before and after.

Thanks!!!

2 Answers

Andrew Shook
Andrew Shook
31,709 Points

Jeremy Dortch, the output is correct. The first Jordan is being printed because this line:

var friendNumber = 1; 
console.log(friends[friendNumber]);

//actually printing
console.log(friends[1]);

Remember, arrays are zero indexed, meaning that they start counting at zero and not one.

array[

0 => "Jake",
1 => "Jordan",
2 => "Will",
3 => "Jordi"
4 => "Jon".
]

So when you tell JavaScript to get position 1 you are really telling it to get the second item in the array.

Now in the for loop, you are telling JS to start at position 0:

for(var i=0; i < friends.length; i+=1)

Position zero is Jake. So first you tell it to print position 1, Jordan, then you tell it to print the whole array starting at position 0 and going through position 4 ( Jake, Jordan, Will, Jordi, Jon). So that's why is prints :

`` Jordan Jake Jordan Will Jordi Jon

Jack Choi
Jack Choi
11,420 Points

I think the output looks correct. The first "Jordan" is being printed by the console log here and maybe that's what's throwing it off:

var friendNumber = 1; console.log(friends[friendNumber]);

newline is your friend!