Aamina Khalid
Web Developer
HOISTING
IN JAVASCRIPT
Variables and Functions - What
Happens Behind the Scenes?
Aamina Khalid Web Developer
WHAT IS HOISTING?
Hoisting in JavaScript is the process
through which variable, function
declarations and classes are moved
to the top of their scope, regardless
of where they're actually defined
Variables declared with var are hoisted
but initialized as undefined.
Aamina Khalid Web Developer
VARIABLE HOISTING
Output = undefined
Cannot access 'b'
before initialization
Cannot access 'c'
before initialization
var is hoisted and initialized as undefined
let and const are hoisted but not initialized.
Aamina Khalid Web Developer
TEMPORAL DEAD ZONE
Variables declared with let and const have
a Temporal Dead Zone (TDZ) from the start
of their scope until they’re initialized.
Accessing a let or const variable before its
declaration results in a ReferenceError.
Aamina Khalid Web Developer
FUNCTION HOISTING
Functions declared with the function
keyword are fully hoisted, meaning you
can call them even before they’re
defined in the code.
Function declarations are hoisted with
their definitions.
Aamina Khalid Web Developer
CLASS HOISTING
Classes are also hoisted, but like let and
const, they are not initialized.
Accessing a class before its declaration
throws a ReferenceError
Aamina Khalid Web Developer
BEST PRACTICES
Always declare variables at the top
of their scope.
Use let and const instead of var to
avoid confusion.
Declare functions and classes before
calling or using them.
BONUS POINT
Enable strict mode ('use strict';) to catch
potential errors.