Skip to content

Instantly share code, notes, and snippets.

@jsonberry
Last active February 13, 2017 19:17
Show Gist options
  • Save jsonberry/e8fea88413b398f7e5441577e3969ad1 to your computer and use it in GitHub Desktop.
Save jsonberry/e8fea88413b398f7e5441577e3969ad1 to your computer and use it in GitHub Desktop.
Override const declaration with function scope and let

You can effectively "override" a const if the subsequent declaration is in a nested function scope.

You can also override a const in a block with let, as that will keep the declaration lexically scoped to that block

Example: The JS engine will not allow an override of the const, even though the var is in a nested block scope

function myScopedConst() {
    const myScopedConst = 42;
    console.log('myScopedConst:: before the block ->', myScopedConst);

    { var myScopedConst = 'reassigned';
        console.log('myScopedConst:: inside the block ->', myScopedConst);
    }

    console.log('myScopedConst:: after the block ->', myScopedConst);
}

Example: This will not allow an override of the const, because the const and let are in the same scope

function myScopedConst() {
    const myScopedConst = 42;
    console.log('myScopedConst:: before the block ->', myScopedConst);

    let myScopedConst = 'reassigned';
    console.log('myScopedConst:: inside the block ->', myScopedConst);

    console.log('myScopedConst:: after the block ->', myScopedConst);
}

Example: This will allow an override of the const, because the let is in a nested block scope

function myScopedConst() {
    const myScopedConst = 42;
    console.log('myScopedConst:: before the block ->', myScopedConst);

    { let myScopedConst = 'reassigned';
        console.log('myScopedConst:: inside the block ->', myScopedConst);
    }
    
    console.log('myScopedConst:: after the block ->', myScopedConst);
}

Example: This also will allow for an override of the const

function myScopedConst() {
    const myScopedConst = 42;
    console.log('myScopedConst:: before the block ->', myScopedConst);

    (function deepScope() {
        var myScopedConst = 'reassigned';
        console.log('myScopedConst:: inside the block ->', myScopedConst);
    })();
    
    console.log('myScopedConst:: after the block ->', myScopedConst);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment