0

I have a function in my JavaScript code which iterates over an array called background_check which has elements which are also arrays. I want to see if any element in this nested array is a 0 (each element is either a 0 or a 1). I do this with a for loop iterating over the array and calling the function recursively if any element is an array.

Here is my code:

function loop_checker(background_check) {
    let loop_condition = false
    let count = background_check.length
    for (i=0;i<count;i++) {
        if (typeof background_check[i] === 'object') {
            let x = loop_checker(background_check[i])
            if (x === true) {
                loop_condition = true
            }
        }
        else if (background_check[i] === 0) {
            loop_condition = true
        }
    }
    return loop_condition

The array in question is background_check = [1, 1, 1, 1, [1, 1, [1, 0]]] The function iterates over the first four elements fine. It then gets to the i=4 case and iterates over the smaller array. When the new for loop gets to i=2 it iterates over the smallest list. Once it is all done it goes back down the call stack, but once it gets back to the first call of the function, i=4 has changed to i=3 and so it redoes the 5th element. This repeats infinitely; I cannot figure out why this has happened. I think it may be an issue with the scope of the i variable and recursion messing with that, but I am very new to JS.

P.S. sorry if this is poorly or incorrectly formatted, this is my first question. Thanks in advance!

6
  • 7
    Make i a local variable. You're overwriting it in the recursive call. Commented Sep 11, 2024 at 15:45
  • 2
    In general, all variables should be local unless you have a reason to do otherwise. Commented Sep 11, 2024 at 15:46
  • 3
    Also, once you set loop_condition = true you should just return it, there's no need to keep looping. Commented Sep 11, 2024 at 15:47
  • 2
    I think I would start by assuming true, then return false immediately after finding a 0. You can short-circuit your loop and not have to iterate through everything. Commented Sep 11, 2024 at 15:47
  • 2
    You may want to check out the Array.some() function. Commented Sep 11, 2024 at 15:48

0

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.