Declarations let, const and class Can’t be Redeclared
Version: ES2015
Level: Beginner
When declaring variables with let
, const
, and class
, you’ll need to be sure not to duplicate declarations of the same name in the same scope. Doing so will create an error.
let num = 1;
let num = 2;
// SyntaxError: Identifier 'num' has already been declared
This is not the case with var
and function
declarations. They can be repeated without producing an error.
var num = 1;
var num = 2; // Ok, num = 2
If you mix these declarations, for example using both let
and var
with the same identifier name, the let
behavior will be used; that is, the redeclaration will not be allowed.
var num = 1;
let num = 2;
// SyntaxError: Identifier 'num' has already been declared
You can redeclare variables of the same name in different scopes, even if just an arbitrary block scope (when using let
, const
, and class
which are block scoped).
let num = 1;
{
let num = 2; // Ok, no conflict
}
Note: As of Chrome version 80, you can also redeclare let
and class
in multiple entries within the JavaScript console without there being an error. Attempting to redeclare a const
, however, will still produce a SyntaxError.
More info: