Access element of an array element

Hello. How can I access the element of an array element with for.

Could you post the code behind that, rather than a screenshot, as it’ll make it easier to help?

At it’s very simplest, you could do something like this to access the different array elements

let myArray = ['Tom', 'Dick', 'Harry'];

console.log(myArray[0]); // Tom
console.log(myArray[1]); // Dick
console.log(myArray[2]); // Harry
1 Like

I found thank you

It used to be for loops that were used to access array elements, but those require you to define more variables to keep track of where you are in the loop.

var i;
for (i = 0; i < myArray.length; i += 1) {
    console.log(myArray[i] + " is " + i + " in the array");

You could move the var inside of the for loop, but then code linters would yell at you for initialising variables halfway through the code.

Better techniques now exist as methods on the array itself. For example, the forEach method.

myArray.forEach(function (item, i) {
    console.log(item + " is " + i + " in the array");

Then you have fancier techniques, where you can use arrow functions and template literals to simplify things.

    (item, i) => console.log(`${item} is ${i} in the array`)

But at a minimum, we are recommended to stay away from for loops as there are almost always better techniques, and to use the array iteration methods like forEach, every, map, filter, find, and reduce instead.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.