0

Here are two working versions (for Node.js) of the same recursive function.

Version 1

function getDependencies(mod, result) {
  result = result || []
  var dependencies = mod.dependencies || []
  Object.keys(dependencies).forEach(function(dep) {
    var key = dep + '@' + mod.dependencies[dep].version
    if (result.indexOf(key) === -1) result.push(key)
    getDependencies(mod.dependencies[dep], result) // COMPARE THIS LINE
  })
  return result.sort()
}

Version 2

function getDependencies(mod, result) {
  result = result || []
  var dependencies = mod.dependencies || []
  Object.keys(dependencies).forEach(function(dep) {
    var key = dep + '@' + mod.dependencies[dep].version
    if (result.indexOf(key) === -1) result.push(key)
    result = getDependencies(mod.dependencies[dep], result) // COMPARE THIS LINE
  })
  return result.sort()
}

How does version 1 of the function work, as compared to version 2, without explicitly setting the result variable?

2
  • Is your semi-colon key broken? Commented Nov 2, 2014 at 6:17
  • This is a Node.js solution from Nodeschool. Commented Nov 2, 2014 at 6:17

1 Answer 1

1

result.push(key) and result.sort() both modify the result array that was passed in as an argument. So there's no need to assign it again in the caller.

Sign up to request clarification or add additional context in comments.

3 Comments

So is it changed because of pass by reference? If getDepenencies() is recursively called multiple times, I do not understand how the results "add up" and are finally returned as one value.
When you pass or assign an object or array, you get a reference to the same object/array, it doesn't make a copy. So all the recursive calls are operating on the same result array.
@user3477405 - there's only one array. When you pass it to a function, no copy is made - it's the same array. So, if a function modifies it, the original is modified. No need to return it. It isn't technically pass by reference, more like pass by pointer.

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.