Block scoping, let, and const

As mentioned earlier, in ES6, you can use let to define variables or use const to define constants, and they will have block-level scope. And in the same scope, you can not redefine a variable using let. Also, you cannot access a variable or a constant that is defined with let or const before its declaration, since there is no variable hoisting with let or const.

Let's see the following workout example:

1.  function workout() {
2. let gym = 'Gym A';
3.
4. const gymStatuses = {'Gym A': 'open', 'Gym B': 'closed'};
5. for (let gym in gymStatuses) {
6. console.log(gym + ' is ' + gymStatuses[gym]);
7. }
8.
9. {
10. const gym = 'Gym B';
11. console.log('Workout in ' + gym);
12. // The following will throw TypeError
13. // gym = 'Gym C';
14. }
15.
16. console.log('Workout in ' + gym);
17.
18. {
19. function gym () {
20. console.log('Workout in a separate gym');
21. }
22. gym();
23. }
24.
25. if (gymStatuses[gym] == 'open') {
26. let exercises = ['Treadmill', 'Pushup', 'Spinning'];
27. }
28. // exercises are no longer accessible here
29. // console.log(exercises);
30.
31. try {
32. let gym = 'Gym C';
33. console.log('Workout in ' + gym);
34. throw new Error('Gym is closed');
35. } catch (err) {
36. console.log(err);
37. let gym = 'Gym D';
38. console.log('Workout in ' + gym);
39. }
40. }
41. workout();

In line 2, we declare the gym variable, and it is visible in the workout() function body. In line 5, we declare the gym variable within the for loop block. It shadows the gym variable declared in line 2 and is only accessible within that for loop block.

In lines 9 to 14, we declare a new scope using a block statement. The gym constant declared in line 10 is only accessible within that scope. And as you can see in line 13, assigning a value to a constant will cause TypeError.

In line 16, the gym variable is back to the one declared in line 2. In lines 18 to 23, we declare the gym function and it is only accessible within that block.

In line 26, we define the exercises variable within the if block. And as you can see from line 29, it is no longer accessible outside the if block.

In lines 31 to 39, we declare a try-catch block. As you can see in lines 32 and 37, the try block and catch block are in different scopes.

To wrap up, using let and const, we can archive block-level scope with for loop blocks, if blocks, try-catch blocks, and block statements, as well as switch blocks.

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

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