Search code examples
javascriptfor-loopspreadfor-of-loop

For of and for loop different results


Can anyone explain, why the first solution using a regular for loop infinitely loops, whereas the second solution using a for of loop doesn’t. The code is identical, so I would expect the same results.

const flatten = (arr) => {
    let newArr = []
    for (i=0; i < arr.length; i++) {
        if(Array.isArray(arr[i])) {
            newArr = [...newArr, ...flatten(arr[i])]
            console.log(newArr)
        } else {
            newArr.push(arr[i])
        }
    }
    return newArr
}
// const flatten = (arr) => {
//     let newArr = []
//     for (let el of arr) {
//       if (Array.isArray(el)) {
//           console.log(el, 'i am el')
//         newArr = [...newArr, ...flatten(el)]
//         console.log(newArr)
//       } else {
//         newArr.push(el)
//         console.log(el, 'i am just reg non array element')
//       }
//     }
//     return newArr
//   }
flatten([[1],[2],3,[[4,5]], [6, 7]])

Solution

  • You're missing a var or let declaration for i in your for loop to make it local, so every time you call flatten the value gets reset. Change

    for (i=0; i < arr.length; i++) {
    

    to

    for (var i=0; i < arr.length; i++) {
    

    and the code works as expected:

    const flatten = (arr) => {
        let newArr = []
        for (let i=0; i < arr.length; i++) {
            if(Array.isArray(arr[i])) {
                newArr = [...newArr, ...flatten(arr[i])]
            } else {
                newArr.push(arr[i])
            }
        }
        return newArr
    }
    console.log(flatten([[1],[2],3,[[4,5]], [6, 7]]))