Let declarations

Let declarations are thankfully far simpler than var declarations. They will be scoped to their nearest environment (whether it is a block, a function, a module, or the global environment) and have no complicated hoisting behaviors.

Their ability to be scoped to a block means that a let declaration inside a block will not have an effect on the outer function scope. In the following code, we can see three different environments (scopes) with a respective place variable in each:

let place = 'outer';

function foo() {
let place = 'function';

{
let place = 'block';
place; // => "block"
}

place; // => "function"
}

foo();
place; // => "outer"

This demonstrates two things to us:

  • Declaring via let will not overwrite or mutate a variable by the same name in an outer scope
  • Declaring via let will allow each scope to have its own variable, invisible to outer scopes

When you use let in either for(;;), for...inor for...of constructs, even outside of the following block, then that let declaration will be scoped as if it were inside the block. This makes sense intuitively: when we initialize a for loop with let declarations, we naturally expect those to be scoped to the for loop itself and not outside of it:

for (let i = 0; i < 5; i++) {
console.log(i); // Logs: 0, 1, 2, 3, 4
}
console.log(i); // ! ReferenceError: i is not defined

We should only use let if we expect the variable to be reassigned at some later point. If no new assignment will occur, then we should prefer constas it gives us a little bit of extra peace of mind.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.89.24