Daniel Thompson
Daniel Thompson

Reputation: 2351

JavaScript scope (recursion) -- argument value overwritten by return value without explicit declaration

My first solution to an in order tree traversal worked off of the return value of the recursive function calls:

BST.prototype.inOrder = function(node, array){
   if(!node){ return []; }
   if(!array){ array = []; }

   return this.inOrder(node.left).concat([node.val], this.inOrder(node.right))

}

But then I saw that it can be also solved with the code below, and I am confused as to how the 'array' value is being persisted..

BST.prototype.inOrder = function(node, array){
  if(!node){ return []; }
  if(!array){ array = []; }
  this.inOrder(node.left, array);
  array.push(node.val);
  this.inOrder(node.right, array)
  return array
}

When the first recursive function call returns, is it overwriting the value of array within the scope of that function? Why is it doing that?

Upvotes: 0

Views: 245

Answers (1)

Bergi
Bergi

Reputation: 664764

This is an overloaded function that would be called without a second argument in the first call, and in that case the variable is initialised with an empty array. A better way to write this might be

BST.prototype.appendInOrder = function(node, array) {
  if (!node) return;
  this.appendInOrder(node.left, array);
  array.push(node.val);
  this.appendInOrder(node.right, array);
}
BST.prototype.inOrder = function(node) {
  var array = [];
  this.appendInOrder(node, array);
  return array;
}

Upvotes: 2

Related Questions