Tricky question

I saw something in comments, that the code doesn’t work if you don’t assign arr.length to a variable and I wanted to check, and it’s true, but I don’t understand why. Can someone explain me why it doesn’t work?

The solution code:


function dropElements(arr, func) {
  
  var times = arr.length;
  for (var i = 0; i < times; i++) {
    if (func(arr[0])) {
      break;
    } else {
      arr.shift();
    }
  }
  return arr;
}

// test here
dropElements([1, 2, 3, 4], function(n) {
  return n >5;    // returns []
});

Without variable:

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

// test here
dropElements([1, 2, 3, 4], function(n) {
  return n >5;   // returns [3, 4] - wich is wrong!
});

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36.

Challenge: Drop it

Link to the challenge:

Hello~!

The reason you need to assign arr.length to a variable is that your loop iterates through arr and removes elements. This means arr.length is decreasing, and since your loop terminates based on arr.length, it terminates early. Assigning arr.length to a variable ensures that your loop’s conditions aren’t changing.

2 Likes