Class and Function Hoisting in JS

An important difference between function declarations and class declarations is that while functions can be called in code that appears before they are defined, classes must be defined before they can be constructed.

class hoisting

Classes defined using a class declaration are hoisted, which means that JavaScript has a reference to the class. However the class is not initialized by default, so any code that uses it before the line in which it is initialized is executed will throw a ReferenceError.

    const p = new Rectangle(); // ReferenceError
    class Rectangle {}

This occurs because while the class is hoisted its values are not initialized.

Function and class expression hoisting

Function expressions and class expressions are not hoisted.



Read More