Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Snippets - Identifier has already been declared

I wrote this in a Chrome snippet:

let myVar = someValue;
 

And when I try to run it 2nd time, it says the variable has already been declared and throws an error at first line.

The error is:

Uncaught SyntaxError: Identifier 'myVar' has already been declared at :1:1

And of course, this would be the default behavior for the Console but it doesn't seem to make much sense here..

Is this intended? Is there any way around this?

like image 475
iuliu.net Avatar asked Jan 17 '17 14:01

iuliu.net


3 Answers

Use block scope and wrap it in '{}'.

{
  enter code here
}
like image 183
abhishek gupta Avatar answered Oct 24 '22 03:10

abhishek gupta


I believe you're running into the fact that a let statement can only be used to create a variable once in any given scope. In your example, even though you're using Chrome snippets, if you output window.commitPromotionData right after the let statement you'll see that it is there. That's the scope your let statement is assigning the variable to. Re-running the same snippet essentially tries to create the same variable within window and results in syntax error as documented here.

You have two workarounds:

  1. Obviously the first is to convert any top level let statements to var's
  2. Or create a new block scope for wrapping the code. This can be done for instance by wrapping the code in an IIFE (function(){ ... code ... })()
like image 36
ragamufin Avatar answered Oct 24 '22 03:10

ragamufin


The error is that you declared variable twice in the scope.

You can reload or refresh the page, then you get new scope, the error will vanish.

like image 2
soarinblue Avatar answered Oct 24 '22 03:10

soarinblue