Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Chrome Snippets: Identifier '...' has already been declared

I'm using Google Chrome's Snippets (inside Dev Tools) for some JS development and testing.

When declaring ES6 classes, the console throws an

Uncaught SyntaxError: Identifier 'Foo' has already been declared at...

after the first time it was run.

class Foo {
constructor(val) {
        this.bar = val;
    }
}

var f = new Foo('myVal');
console.log(f.bar); // prints 'myVal'

I did some research and found out that wrapping the code in a block scope with {} would help in avoiding this problem.

But when I do this, although the code runs without error, Chrome doesn't recognize any subsequent edits that I may do to my code.

So, if I changed the above code to the following:

{
    class Foo {
    constructor(val) {
            this.bar = val;
        }
    }
}

var f = new Foo('myVal');
console.log(f.bar); // prints 'myVal'

So far everything works fine.

Now, I realize that there is a problem with my class and I change the code to the following:

{
    class Foo {
    constructor(val) {
            this.bar = 'MyHardcodedVal'; // Here is the changed code
        }
    }
}

var f = new Foo('myVal');
console.log(f.bar); // STILL prints 'myVal'

As you can see, the edits I made to my class are not taking effect.

It appears that Google Chrome has put my code in a sandbox that is immune from my editing.

A way to look behind the scene and see what Google Chrome is doing is to introduce an intentional mistake into the code and then click on the source of the mistake that Chrome shows in the console. There you will see that the code for the class is still the old one and not changed at all, while the code that has been outside of the block scope is up to date.

A few pieces of important information are highlighted: (let) The intentional mistake / ('hardcoded') The change in my class / (VM157) Top and down where you can click to see how the code looks like behind the scenes

Here you can see that behind the scene the edit to the code that was in block scope is not existent

I could always close the tab I am working in and open it again, but that isn't practical.

What am I doing wrong?

Is there a sane way to use Snippets for such tests?

Hope that makes sense!

like image 952
kev Avatar asked Apr 21 '19 15:04

kev


Video Answer


1 Answers

Based off the comments, it sounds like the solution is to wrap the entire snippet in braces.

{
  class Foo {
    constructor(val) {
      this.bar = 'MyHardcodedVal'; // Here is the changed code
    }
  }
  var f = new Foo('myVal');
  console.log(f.bar); // STILL prints 'myVal'
}
like image 98
Kayce Basques Avatar answered Nov 15 '22 06:11

Kayce Basques