Javascript causes crash at start of for-loop before ever looping once

I have a json object that describes the file tree on an external server, when I try to iterate through the values of the object so that I can render the tree as HTML the entire browser crashes and reloads immediately at the start of the loop. Here is my code:

    HGEClient.send("queryfiletree").then(fileTree =>
    {
      let renderFolder = function(parentFolder, folder)
      {
        this.createCatelogFolder(parentFolder, folder);

        for(child of Object.values(folder.children))
          if(child.type == "folder") renderFolder(folder, child);
          else                       this.createCatelogFile(folder, child);
      }


      for(location of Object.values(fileTree)) // Crashes here
        if(location.type == "folder") renderFolder(null, location);
        else                          this.createCatelogFile(null, location);
    });

The object itself isn’t ill-formed and I’m able to iterate on it on the server prior to sending it to the client. I have verified through the debugger using breakpoints that the crash is exactly when location is assigned a value the very first time from Object.values(fileTree)

enter image description here

>Solution :

location also is a globally scoped object at client side, thus for the iteration location needs its own scope, preferably by being a let variable type, otherwise the script does break/crash.

const fileTree = [{
  type: "folder",
  id: "foo",
}, {
  type: "folder",
  id: "bar",
}, {
  type: "file",
  id: "baz",
}];

// `location` needs to be a variable type, preferably `let`
// ---v
for (let location of Object.values(fileTree)) {
  if (location.type === "folder") {
    console.log({ location });
  }
}
.as-console-wrapper { min-height: 100%!important; top: 0; }

Leave a Reply