Drop it challenge

The challenge is to iterate through the array and drop each element until an element returns true. Why does this code not work?

function dropElements(arr, func) {
for(let i = 0; i< arr.length; i++){
  if(func(arr[0]) === true){
  } else{
return arr

console.log(dropElements([1, 2, 3, 4], function(n) {return n > 4;}));

Meanwhile, one of the solutions is

function dropElements(arr, func) {
  // drop them elements.
  let originalLen = arr.length;
  for (let i = 0; i < originalLen; i++) {
    if (func(arr[0])) {
    } else {
  return arr;

I don’t see what makes that code work and mine not work

Challenge: Drop it

Link to the challenge:

In cases like these it can help to just iterate through your own program with pen and paper, see if the results are as you expect. Or if you have learned how to debug in your editor, that can be helpful.

This is a fairly common issue of modifying the array you are iterating over as you go. Your i goes up, but your arr.length in your for loop also goes down, so you are iterating over only half of the element.


The problem is in the head of the for loop. With each iteration, the length of the array gets computed. But because you drop items each iteration not all elements in the array get covered. To avoid that problem the solution computes the array length first in a separate variable that never changes. I hope my explanation makes sense.

1 Like

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