11 - How to fix "Uncaught SyntaxError: Identifier "x" has already been declared" in JavaScript
The important bits
- Uncaught SyntaxError: Identifier "x" has already been declared means that you declared a variable with the let or const keyword, and you are re-declaring it again. This is considered a bad practice and will throw an error with let or const.
Exercise - Now you try it
Transcript
SyntaxError: Identifier "color" has already been declared. Now this one's pretty interesting. Because for the longest time we only had the var keyword in Javascript to declare a variable,
but the var keyword has no checks for if it's already been declared. That means that this code here would cause no errors,
even though this is kind of a bad idea. Is anybody reading this code would be pretty confused as to why your wire declared it twice? So if you really want to reassign it, this is the way to do it: Just leave out the second var keyword. In the last few years, we've had the addition of the let keyword and the const keyword to declare new variables, and so now we have that check. So here we see that we are declaring the color variable and then immediately afterward declaring the color variable again,
and that's why it's throwing an error here.
The solution to this error is to remove the second declaration. Now. Sometimes, maybe you're loading this line here in one javascript file, and then you're loading this one from another javascript file.
But you don't realize that they're not inside a function, so they're both in the same global scope and so they're colliding with each other because of that.
That one,
so that fixes that, and then
const has the same limitation.
The const cannot be renamed, but we'll talk about that in a different episode.
Alright, good luck.
END That's it.