Console.logging [ i ]

Hi there,

If anyone would like to help me, I would like some more insight into this.

let exampleArray = [“Tomato”, “Tomatoe”, “Potato”, “Gelato”];

for (let i = 0; i < exampleArray.length; i++){

When console.log:ed it prints:



for (let i = 0; i < exampleArray.length; i++){

when removing the [ i ], as done above, it prints:

// [object Array] (4) [“Tomato”,“Tomatoe”,“Potato”,“Gelato”]

// [object Array] (4) [“Tomato”,“Tomatoe”,“Potato”,“Gelato”]

// [object Array] (4) [“Tomato”,“Tomatoe”,“Potato”,“Gelato”]

// [object Array] (4) [“Tomato”,“Tomatoe”,“Potato”,“Gelato”]

I do UNDERSTAND why 2 prints the way it does and I KNOW that the setup in 1 will print the way it does, but why does [ i ] get access to each element in the array and print it accordingly, as it does in 1? What is really going on there?

Any input is highly appreciated!

The first one because it first prints the item with the index 0 the above index of 1 and so on. When you are printing an array like this it will have quotes. And I forgot about the second thing you asked. Also don’t forget to format your code. Learn how to here: [How to] Format code in posts

1 Like

As Ethan pointed out, the loop takes your value i and compares it to the value of exampleArray.length. Whenever i is less than the length of the array, it will perform the console.log().

It’s important to know that Array’s are 0 indexed.
That means that if we have an array:

let myArray = [“index0”, “index1”, “index2”]

We can traverse this array by using the for loop you created above because i is incremented every time the loop runs anew.
You can try to put a console.log() for i to see the value change.

I hope this helps :slight_smile:

1 Like

Ah, I understand! Thank you :slight_smile: