ES2015 Lesson 2: Function scope, block scope, constants – Solutions


Exercise 1: Check the following riddle:

Determine the values logged to the console.

Solution:

  • (A) is not printed out, because we accessed guessMe2 in its temporal dead zone, resulting in an error
  • (B) is printed out, the value of guessMe1 comes from the outside, while guessMe2 is assigned a value the line above this console.log statement
  • (C) is printed out, the value of guessMe2 is not influenced by the definition inside the block. In this scope, the definition in line 2 holds
  • (D) and (E) are obviously not printed out, as the arrow function is not called anywhere
  • (F) is printed out with the same values as (C)

Exercise 2: Modify the code such that all six console logs print out their values exactly once, and the printed values are the following:

You are not allowed to touch the console logs, just the rest of the code.

Solution:

In the first block, move the let declaration to the top of the block, to avoid the temporary dead zone belonging to guessMe2 in the first console log. Now that the temporal dead zone is removed, the try-catch block serves no purpose anymore.

In order to execute the fourth and the fifth console logs, we have to invoke the function. Note that self-invoking functions are not necessary anymore in ES2015, as we should only be using block scoped variables anyway, and creating blocks to separate scope is sufficient.

Without moving the declaration of guessMe1 inside the self-invoking function to the top, the console log D would log undefined. Even though it does not make a difference, I also moved the let declaration of guessMe2 to the top.


Exercise 3: Add the linter of your choice to your text editor or IDE. Configure your linter such that you never have to worry about leaving a temporal dead zone unnoticed.

Solution: There is no exact solution to this exercise. Read my article about ESLint if you are interested in learning the basics of linting. Configure the text editor of your choice to run with ESLint.

For var declarations, I used the vars-on-top rule. There was no such rule in ESLint for let and const declarations (proof).

If you go down the line of not allowing var at all, use the no-var rule.

Regarding the temporal dead zone, the no-use-before-define rule parses and spots variable use in the temporal dead zone.