- Global scoping
- Functional scoping
- Lexical scoping
To explore let statement in detail, consider the code snippet given below:
You will get this output for the above code listing:
In the above listing, variable x is declared using the var statement. Hence, the scope of variable x is a function scope. Variable x inside the if statemnet is same variable x which was created outside the if statement. So, when you modify the value of variable x inside the if statement block, it modifies the value for all references of variable x in the function.
To avoid this, you need block-level scoping, and the let statement allows you to create a block-scoped local variable.
Let’s modify the above code snippet and use the let statement to declare the variable:
In the above code snippet, you are declaring scope level local variable x using the let statement. Therefore updating value of variable x inside the if statement will not affect value of variable x outside the if statement.