2

I'm doing a code challenge with the following solution:

let files = {a: {b: true}}
// return 'a/b'

function getPath(file) {
  let output = [];
  for (key in file) {
    if (file[key] instanceof Object) {
      let saved = key
      console.log(`Before getPath ${key}`)
      let paths = getPath(file[key])
      console.log(`After getPath ${key}`)
      paths.forEach((path) => {
        output.push(`${saved}/${path}`)
      })
    } else {
      output.push(`${key}`)
    }
  }
  return output
}

getPath(files)

Why would the "key" changes before and after let paths = getPath(file[key])? In this recursion, there would be two levels of for-in loop. Is it possible that the inner for-in loop is causing the issue due to scope/context problem? Is it because "key" ignores function scope and mutates it?

ethan852
  • 337
  • 6
  • 13
  • 4
    You didn't declare `key` with either var or let so it becomes global. When you call `getPath` in between, the global variable `key` gets changed. – Patrick Evans Dec 08 '16 at 01:27
  • 1
    Just get in the habit of declaring all variables as local, unless you specifically need global variables. – Barmar Dec 08 '16 at 01:33
  • If you had used strict mode, your mistake would have become an error. – Bergi Dec 08 '16 at 01:50

0 Answers0