NOTE: All images from Jonas Schmedtmann's The Complete Javascript Course 2020

Execution Context: Variable Environment

Execution Context: Variable Environment

Hoisting and the TDZ

Variable Environment

Variable Environment

Code Examples

Hoisting Variables

  • at the point where we console.log the variables, var is undefined, while let and const are uninitialized (they are in the TDZ)
    • Hoisted Variables
  • var creates a property on the global window object, while const and let do not
    • Hoisting Example

Hoisting Functions

  • only the regular function addDecl can be accessed before it occurs in the code
  • here addExpr and addArrow are defined as consts so they are in the TDZ
    • Hoisting Functions
  • here addExpr and addArrow are defined as vars so they are undefined at the time they are called, so they can't be called or accept arguments
    • Hoisting Functions
    • Hoisting Functions

Be Careful

  • numPoducts is undefined, which is a falsy value, so it enters the if statement even though it hasn't been initialized yet
    • Hoisting Example
    • this kind of thing would be a hard big to find in a large codebase
    • best practices for clean code (according to Jonas):
      • try to always use const if possible, then let if you really need to change it later
      • declare all variables at the beginning of their scope
      • declare all functions first and only use them after they are declared (even function declarations)

Copyright © 2022