Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading