NOTE: All images from Jonas Schmedtmann's The Complete Javascript Course 2020
Execution Context: Variable Environment
Hoisting and the TDZ
Code Examples
Hoisting Variables
- at the point where we
console.log
the variables,var
is undefined, whilelet
andconst
are uninitialized (they are in the TDZ) var
creates a property on the global window object, whileconst
andlet
do not
Hoisting Functions
- only the regular function
addDecl
can be accessed before it occurs in the code - here
addExpr
andaddArrow
are defined asconst
s so they are in the TDZ - here
addExpr
andaddArrow
are defined asvar
s so they are undefined at the time they are called, so they can't be called or accept arguments
Be Careful
numPoducts
is undefined, which is a falsy value, so it enters the if statement even though it hasn't been initialized yet- 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, thenlet
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)
- try to always use