1

I'm working on an assignment that experiments with different types of loops. I have to use a for loop to console.log each item in the array cars. I can only use a for loop, no other methods such as for each. What am I missing?

I have tried console logging cars but that logs the entire array a number of times equal to the number of strings in the array, which is obviously not correct. I'm also fairly certain that the .length method used in the for loop is incorrect as well.

const cars = ["ford", "chevrolet", "dodge", "mazda", "fiat"];
for (let i = 0; i < cars.length; i++) {
  console.log(cars)
}

3 Answers 3

5

In the above code, you need to log cars[i] to the console:

const cars = ["ford", "chevrolet", "dodge", "mazda", "fiat"];
for (let i = 0; i < cars.length; i++) {
  console.log(cars[i])
}

cars is the array, and to access one item in the array, you need to use the numerical index (in this case i).

You can also eliminate indexes entirely by using a forEach loop, which is often simpler and faster than a traditional for loop:

const cars = ["ford", "chevrolet", "dodge", "mazda", "fiat"];
cars.forEach(car => console.log(car));

Sign up to request clarification or add additional context in comments.

2 Comments

Ah! So much simpler than I had thought. Thank you for the help!
No problem @Jim.
1

cars refers to the entire array. What you want is to access an item in the array by index in the for loop: that can be done by using cars[i]:

const cars = ["ford", "chevrolet", "dodge", "mazda", "fiat"];
for (let i = 0; i < cars.length; i++) {
  console.log(cars[i]);
}

Even better: you an use forEach instead, which is way more readable:

const cars = ["ford", "chevrolet", "dodge", "mazda", "fiat"];
cars.forEach(car => {
  console.log(car);
});

Comments

1

You can use foreach too

const cars = ["ford", "chevrolet", "dodge", "mazda", "fiat"];
cars.forEach(function(element, index) {
  console.log(element, index);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.