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 JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Using For Loops with Arrays

Printing a specific number of array

What if, i want to extract only item 3 in array, can i do that while using for loop?

Yeah you can, insead using array.lenght use the number that you want to use

Jesus Mendoza But, how can i while i am in for loop?

In the video you're using an array called students right?

var students = ['Sascha', 'Lynn', 'Jennifer', 'Paul'];
for (var i = 0; i < 3; i++) {
   console.log(students[i]);
}

Note that instead using

i < students.lenght
on the foor loop I used
i < 3

Jesus Mendoza Your solution will print out index 0 through 2. The console will log Sascha, Lynn and Jennifer when the goal is to only log Paul. Chris Wiley has the right answer.

Yea Melissa you're and Chris are right! It seems that I did not understand the question.

2 Answers

This should do what you want it to:

var listOfItems = ['Item 1', 'Item 2', 'Item 3', 'Item 4'];
for (var i = 0; i < listOfItems.length; i++) {
if ( i === 2 ) {
   console.log(students[i]);
}
}

This will print to the console the third item in the list

Try a conditional; e.g. an if statement...

for (var i = 0; i < students.length; i++){ if (i === 2){ // The third item is index # 2 console.log(students[i]); // This will send the 3rd Student in the array to the console. } }