-3

When I declare a variable using the let keyword that is already declared using the let keyword in the same scope, then it throws a SyntaxError exception. Consider this example:

let a = 0;
let a = 1; // SyntaxError

function foo() {
    let b = 2;
    let b = 3; // SyntaxError

    if(true) {
        let c = 4;
        let c = 5; // SyntaxError
    }
}

foo();

I know that example can't execute because we can't re-declare variable with let but we can do it with var. So I want to know clearly what happen insight nodejs and browser ?

"I wanna know how browser or nodejs process this situation ?"

Can anyone explain?

Mike Graham
  • 91
  • 1
  • 10
  • 1
    I'm not sure anything happens in the browser or in node. I'm pretty sure the parser blocks your code before even dreaming of interpreting it, because the syntax doesn't allow the redeclaration. – Federico klez Culloca Oct 02 '18 at 10:55
  • This is intentional behavior, it's one of the desirable facets of `let` that make it more useful than `var`. – user229044 Oct 02 '18 at 11:12

2 Answers2

2

let gives you the privilege to declare variables that are limited in scope to the block, statement of expression unlike var, but you can not re-declare the same variables in the same scope using let. If you want to change the value of the variable in the same scope just remove the declaration part:

let a = 0;
a = 1;

function foo() {
    let b = 2;
    b = 3;

    if(true) {
        let c = 4;
        c = 5;
    }
}

foo();

In your example a SyntaxError is thrown. So what is happening and why this error is thrown? Simply you are not conforming the rules for the syntax (because you try to redeclare let variable which is wrong syntax according to the Javascript engine) and the Javascript engine (both in the Browser and in NodeJS) encounters this wrong syntax when parsing the code and throws a SyntaxError.

Simeon Stoykov
  • 891
  • 7
  • 11
0

Let and Const Declarations will throw an error if you redeclare them in the same scope. However, they follow different rules in that their declarations aren't hoisted and their scope is limited to the first set of containing curly braces.

Reference: https://www.quora.com/What-does-happen-if-we-re-declare-a-variable-in-JavaScript

Akhilraj R
  • 69
  • 5