a simple reminder whenever I context-switch from whichever of the gazillion
languages I write in back to ES6. There are a few subtleties regarding
Hoist or Throw Up
Calling a variable without having it declared will result to a
var declarations are hoisted to the top of a function which
means that all declared variables are available anywhere in the function
regardless of where they were declared.
Now with hoisting we can only promise that a variable will be accessible. It isn’t defined yet. Nothing meaningful is assigned to it yet. .
undefined Until Assigned
Declared variables are
undefined unless a value is explicitly assigned to
them. Eventhough declarations are hoisted to the top of the block,
definitions apply whenever the assignment is handled.
Even if the variable of interest happened to be defined in a parent scope, a
var will be
undefined by default within the scope in which it is
It sometimes helps to imagine that any
var variable declaration adds the
var x = undefined; at the top of the scope.
let it Be
It is important to remember that hoisting is a bit different between
const’s. Instead of being hoisted to the top of the function
const are hoisted to the top of the containing block
which could be a
for block or anything else where a block is
described in addition to
In that sense the scoping of
const statements is a bit more
const declaration would be limited to the scope of
the if-block within which it was declared in our current example leaving
someone without its sidekick.
A declared variable is set to
undefined, even if the parent scope contains
a variable by the same name.
Climbing the Scope Ladder
scope ladder until it arrives at a scope that does define the variable of
var declarations the hoisting boundary is the function.
const declarations the hoisting boundary is defined by the
It is useful to know the mechanics of hoisting, although for readabilities’ sake it would be advised to not depend on this language feature too much.