In JavaScript, a function expression (defined using let
, const
or var
) is not hoisted. This means that you cannot use a function expression before it's evaluated (i.e. until the relevant line of code is executed). If you try to access it before, you will get an error.
Function Expressions Defined Using let
or const
When you use let
or const
to define a function expression, the following is true:
- The variable declaration/name does get hoisted, however, it is uninitialized;
- The variable assignment (i.e. function definition in this case) is not hoisted, and is inaccessible till the relevant line of code is executed/evaluated;
- Accessing the variable before the relevant line of code is executed/evaluated, results in a
ReferenceError
(because the variable is in a "temporal dead zone").
For example:
// ReferenceError: notHoisted is not defined notHoisted(); const notHoisted = function() { console.log('foo'); };
// ReferenceError: notHoisted is not defined notHoisted(); let notHoisted = function() { console.log('foo'); };
Function Expressions Defined Using var
When you use var
to define a function expression, the following is true:
- The variable declaration/name does get hoisted, however, it is initialized to
undefined
; - The variable assignment (i.e. function definition in this case) is not hoisted, which is why in lines before it is defined, it equals to
undefined
(as that's the value the variable is initialized to); - Since
undefined
is not a function, aTypeError
is thrown if you try to call the function anywhere before the line where it is defined.
For example:
// TypeError: notHoisted is not a function notHoisted(); var notHoisted = function() { console.log('foo'); };
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.