Guys, please explain how it works?

filterRangeInPlace function(arr, a, b) {

 for (let i = 0; i < arr.length; i++) {
 let val = arr[i];

 // remove if outside interval
 if (val < a || val > b) {
 arr.splice(i, 1);
i--;
}
}

}

let arr = [5, 3, 8, 1];

filterRangeInPlace(arr, 1, 4); // removed number outside the range 1..4

alert( arr ); // [3, 1]

What makes i -?????
April 3rd 20 at 18:41
3 answers
April 3rd 20 at 18:43
Solution
It's very simple. Look, we have an array of const numbers = [1, 2, 4, 8];. We pass him on the cycle for, while not pre-storing the array length, therefore if to remove in the cycle every time the current index, the next iteration will be calculated the condition i < arr.length, but 1 element that we removed, and hence the loop will terminate early. To avoid this, i save 1. In that moment, when a member is deleted, i with the next iteration "remains in place".
April 3rd 20 at 18:45
April 3rd 20 at 18:47
This is a unary operator. It decrements a variable by one
Wikipedia

Find more questions by tags JavaScript