11 - How to fix "Uncaught SyntaxError: Identifier "x" has already been declared" in JavaScript

The important bits

Exercise - Now you try it

// Fix the error let name = "gaston"; let name = "adam";

Transcript

0:01 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,

0:16 but the var keyword has no checks for if it's already been declared. That means that this code here would cause no errors,

0:27 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,

0:58 and that's why it's throwing an error here.

1:02 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.

1:17 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.

1:29 That one,

1:31 so that fixes that, and then

1:35 const has the same limitation.

1:40 The const cannot be renamed, but we'll talk about that in a different episode.

1:48 Alright, good luck.

1:51 That's it.

END