• Javascript Scope Related Doubt

    From Gaurav Kumar Arya@21:1/5 to All on Fri Aug 6 02:53:48 2021
    Hello Sir/Madam,

    I have one doubt regarding this question
    (function fn() {
    {
    let a = 10;
    {
    var a = 20;
    console.log(a);
    }
    }
    })();

    why it is giving syntax Error ?
    I know this is illegal shadowing concept but when I put braces before let a =10, then that a variable has block scoped and var a is function scoped, here after adding curly braces before let a , I have create new scope and after fn(){ // here var a is
    hoist}, then if both are in different scope , why it is showing error.

    Please help in explaining this concept.

    Thank You

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Julio Di Egidio@21:1/5 to gaura...@gmail.com on Fri Aug 6 03:34:22 2021
    On Friday, 6 August 2021 at 11:53:53 UTC+2, gaura...@gmail.com wrote:
    Hello Sir/Madam,

    I have one doubt regarding this question
    (function fn() {
    {
    let a = 10;
    {
    var a = 20;
    console.log(a);
    }
    }
    })();

    why it is giving syntax Error ?
    I know this is illegal shadowing concept but when I put braces before let a =10, then that a variable has block scoped and var a is function scoped, here after adding curly braces before let a , I have create new scope and after fn(){ // here var a is
    hoist}, then if both are in different scope , why it is showing error.

    They are not in a different scope: "let a" is in the *top* block scope of the function, which is the entire function, but so is "var a", as that's how var scoping works.

    Please help in explaining this concept.

    Have a read through this and related: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let>
    The very last example is your case.

    HTH,

    Julio

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)