Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Using Array Indices

The script.js file contains an array of string values -- the names of players in a game. Let's practice using array

The script.js file contains an array of string values -- the names of players in a game. Let's practice using array indices to access individual names in the array. Log the first name of the array using the console.log() method.

var players = ['Jim', 'Shawna', 'Andrew', 'Lora', 'Aimee', 'Nick'];
<!DOCTYPE html>
  <meta charset="utf-8">
  <title>JavaScript Loops</title>
<script src="script.js"></script>

3 Answers

Tom Nguyen
Tom Nguyen
33,482 Points


const players = ['Toni', 'Anwar', 'Mali', 'Carlos', 'Cormac', 'Sariah'];
Sean T. Unwin
Sean T. Unwin
28,660 Points

The goal is to get the first value of the Array. The Array is called players and the value we are seeking is 'Jim'. Now, the value is mostly irrelevant because we only care about the first item in the Array, it just happens to be 'Jim'.

As KWAME ADJEI mentioned, Arrays use zero-based indexing. Arrays have Key/Value pairs, similar to an Object. The difference being is that Arrays cannot have named Keys so they are numbered and start at zero (0).

So the way to get that first Array item is to reference the variable the Array is named, players, then use bracket notation to get the first item, which is Key 0. This would look like: players[0]. Simply place that inside the brackets of console.log().

4,627 Points

I'm not sure of the question but arrays are 0 based so the first index of the array is 0.

Try console.log('Jim'[0]);