Hoisting in JavaScript

https://scotch.io/tutorials/understanding-hoisting-in-javascriptarrow-up-right

What is Hoisting?

  • JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.

    • no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local.

undefined vs ReferenceError

undefined

  • In JavaScript, an undeclared variables is assigned the value undefined at execution and is also of type of undefined.

ReferenceError

  • In JavaScript, a ReferenceError is thrown when trying to access a previously undeclared variable.

The behavior of JavaScript when handling variables becomes nuanced because of hoisting!

Hoisting variables

  • all undeclared variables are global variables

ex)

var

function scoped

ex)

  • JavaScript has hoisted the variable declaration

let

block scope

ex1)

ex2)

  • We should declare then assign our variables to a value before using them!

const

Introduced in ES6 to allow immutable variables

ex1)

ex2)

ex3)

  • the variable is hoisted to the top of the block

  • must be both declared and initialized before use.

Hoisting functions

JavaScript functions

  1. Function declarations

  2. Function expressions

Function declarations

Hoisted completely to the top

ex)

Function expressions

Not hoisted

ex)

Order of precedence

  1. Variable assignment takes precedence over function declaration

  2. Function declarations take precedence over variable declarations

Function declarations are hoisted over variable declarations but not over variable assignments!

Hoisting classes

JavaScript Classes

  1. Class declarations

  2. Class expressions

Class declarations

Hoisted like function declarations

ex)

  • you have to declare a class before you can use it

Class expressions

Not hoisted like function expressions

ex)

Last updated