JS Coding Questions Logo
JS Coding Questions
#307💼 Interview💻 Code

Can I redeclare let and const variables

Advertisement

728x90

No, you cannot redeclare let and const variables. If you do, it throws below error

bash
1Uncaught SyntaxError: Identifier 'someVariable' has already been declared

Explanation: The variable declaration with var keyword refers to a function scope and the variable is treated as if it were declared at the top of the enclosing scope due to hoisting feature. So all the multiple declarations contributing to the same hoisted variable without any error. Let's take an example of re-declaring variables in the same scope for both var and let/const variables.

javascript
1var name = "John";
2
3function myFunc() {
4  var name = "Nick";
5  var name = "Abraham"; // Re-assigned in the same function block
6  alert(name); // Abraham
7}
8
9myFunc();
10
11alert(name); // John

The block-scoped multi-declaration throws syntax error,

javascript
1let name = "John";
2
3function myFunc() {
4  let name = "Nick";
5  let name = "Abraham"; // Uncaught SyntaxError: Identifier 'name' has already been declared
6  alert(name);
7}
8
9myFunc();
10
11alert(name);

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 51

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
307of476