A higher order function is a function that takes one or more functions as arguments, or returns a function as its result.
In JavaScript, declarations are hoisted. Variables declared using let
and const
are hoisted to the top of their block scope but are not initialized. While the block is aware of the variable, it cannot be used until after it has been declared. This period is known as the temporal dead zone
—the time between the start of the block and the point where the variable is declared.
console.log(a); // undefined
console.log(b); // Uncaught ReferenceError: Cannot access 'b' before initialization
var a = 100;
let b = 1000;
console.log(window.a); // prints 100
In the example above:
- The variable
a
, declared withvar
, is hoisted and attached to the global object (e.g.,window
in browsers). - The variable
b
, declared withlet
, is hoisted but resides in the block scope and cannot be accessed until it is initialized. Attempting to access it beforehand results in aReferenceError
.
When you run the example, you’ll notice:
- Memory for
a
is allocated in the global object (window
in browsers). - Memory for
b
is allocated in a separatescript
scope and is inaccessible until the variable is initialized.
Common errors with let
and const
Using let
before declaration
Attempting to use a let
variable before its declaration results in a ReferenceError
.
carName = "Volvo";
let carName;
// Uncaught ReferenceError: Cannot access 'carName' before initialization
Using const
before declaration
Using a const
variable before its declaration results in a SyntaxError
, preventing the code from running altogether.
carName = "Volvo";
const carName;
// SyntaxError: Missing initializer in const declaration
Summary
- Variables declared with
var
are hoisted and initialized withundefined
. - Variables declared with
let
andconst
are hoisted but remain uninitialized, existing in the temporal dead zone until their declaration is encountered. - Attempting to access
let
variables before declaration results in aReferenceError
. - Attempting to access
const
variables before declaration results in aSyntaxError
.
What are your thoughts on this post?
I’d love to hear from you! Click this link to email me—I reply to every message!
Also use the share button below if you liked this post. It makes me smile, when I see it.