0

I'm at the very very very beginning of JS learning curve.
I am trying to use a loop on an array (containing six types of food) and then only print out the even elements:

const foodArray = ["pizza", "tacos", "fruit", "veggies", "hummus", "tea"];

foodArray.forEach(food => {
  if (foodArray.length % 2 = 0) {
  console.log(`${food}`); 
  }
});

Is this totally wrong? Should I use either for or while loop in association with the if conditional statement?

4
  • 1
    You can do what you have in mind but the code is not correct: first of all you have to check whether the index is odd or even (not the array length) then, as arrays starts from index 0, if you want the 2nd, 4th, 6th, etc. element, you have to print the elements that have an odd index Commented Dec 14, 2020 at 16:23
  • Ach you're so right @secan! would this be considered okay then? const foodArray = ["pizza", "tacos", "fruit", "veggies", "hummus", "tea"]; for (i = 0; i < foodArray.length; i += 2) { console.log(foodArray[i+1]); } Commented Dec 14, 2020 at 17:08
  • Yes, that is perfectly valid, although you could start the loop from 1 (for (let i = 1; i < foodArray.length; i += 2) { console.log(foodArray[i]) }) so that you avoid the first unnecessary loop and you can use directly foodArray[i] instead of foodArray[i+1] Commented Dec 14, 2020 at 17:13
  • beautiful. true! thank you again Commented Dec 14, 2020 at 17:18

5 Answers 5

1

A normal for-Loop would be the way to go in my opinion. The forEach-loop is better if you don't need to reference the index of the elements. In your case you need the index, because it tells you whether an element is even or not. Here is a little example:

const foodArray = ["pizza", "tacos", "fruit", "veggies", "hummus", "tea"];
for (i = 0; i < foodArray.length; i++) {
  if (i % 2 === 0) {
    console.log(foodArray[i]);
  }
}

A forEach loop of course can also take the index using another parameter in the lambda expression, like in sabbit.alam's answer, but imo a normal for-Loop is better for learning in the beginning.

An even better for-Loop would be the following, where the if-expression is nested in the for-Loop itself by incrementing in 2-steps:

const foodArray = ["pizza", "tacos", "fruit", "veggies", "hummus", "tea"];
for (i = 0; i < foodArray.length; i += 2) {
  console.log(foodArray[i]);
}
Sign up to request clarification or add additional context in comments.

Comments

1

There is a mistake instead of equality checking you have been using = as assignment operator here (foodArray.length % 2 = 0) Even if you fix that issue by using === instead of = it will print all the values if the length of food array is even otherwise it will print nothing.

You should do the following,

const foodArray = ["pizza", "tacos", "fruit", "veggies", "hummus", "tea"];

foodArray.forEach((food, index) => {
  if (index % 2 === 0) {
  console.log(`${food}`); 
  }
});

That will print all the even indexed value.

Comments

0

Always try to avoid forEach loop because it will increase the call stack size(On every loop new function is called) having said that Here is the correction on your code.

foodArray.forEach((food, index)=> { if (index % 2 === 0) { console.log(food); } });

Comments

0

2 ways :

const foodArray = ["pizza", "tacos", "fruit", "veggies", "hummus", "tea"]

foodArray.forEach((food, index) =>
  {
  if (!(index %2))  console.log(`s1 -> ${food}`)
  })
  
console.log('-----------')
// or 
for ( let i=0; i<foodArray.length; i+=2 )
   console.log(`s2 -> ${foodArray[i]}`)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

0

There is a way to achieve this wtihout doing the index modulus check - simply increment the index by 2 on each iteration instead of 1. This is more efficient because it prevents the check on each iteration (not important on this list - but imagine if you had an array of 1 million items.

const foodArray = ["pizza", "tacos", "fruit", "veggies", "hummus", "tea"];

for (i = 0; i < foodArray.length; i+=2) {
  console.log(foodArray[i]); // gives pizza fruit hummus
}

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.