Search code examples
javascripttreeinorder

Cannot read property 'push' of undefined when when using nested functions


Why does the following code work

const inorderTraversal = (root) => {
    let out = []

    const traverse = (node) => {
        console.log(node)
        if (!node) return
        traverse(node.left)
        out.push(node.val)
        traverse(node.right)
    }
    traverse(root)
    return out
};

but this one does not

const inorderTraversal = (root) => {
    let out = []

    const traverse = (node,arr) => {
        if (!node) return
        traverse(node.left)
        arr.push(node.val)
        traverse(node.right)
    }
    traverse(root,out)
    return out
};

I need to modify the algorithm for multiple binary trees but when sending the array as a parameter instead of a global variable I get an Cannot read property 'push' of undefined error.


Solution

  • In your second second script, you wrote traverse(node.right), but, because your traverse function now has two parameters and you only pass in one, arr is undefined. Then, in the recursive function call, you get a warning on the statement arr.push(node.val) because you are trying to call the push method on arr even though the variable is undefined. To fix the error, add arr as the second parameter of the function call.