Break not returning the desired output

Tell us what’s happening:
Describe your issue in detail here.
In this my simple approach is to iterate over the whole array, break the loop as soon as function returns true. And till when the function returns false remove that element from the array. But despite of break the loop is iterating through the whole array length.

   **Your code so far**

function dropElements(arr, func) {
for(var i=0;i<arr.length;++i){

dropElements([1, 2, 3], function(n) {return n < 3; });
   **Your browser information:**

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

Challenge: Drop it

Link to the challenge:

double check how your code behaves. As soon as the function returns true, your loop breaks and nothing executes. In the example case with [1,2,3], the loop breaks on the first element and does nothing to the array

your title says “Break not returning the desired output” - note that a break does not return, your function is always returning undefined

Your code is doing the dangerous thing of modifying both the index i and the length of the array itself. This can often lead to unintentionally skipping over elements.
e.g. say you find func(arr[i]) to be false at index 0, and splice, the element you want to look at next was index 1 but now is at 0. However your i has moved on to 1.

1 Like

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