Learn JavaScript
  • Introduction
  • Basics
    • Comments
    • Variables
    • Types
    • Equality
  • Numbers
    • Math
    • Basic Operators
    • Advanced Operators
  • Strings
    • Creation
    • Replace
    • Length
    • Concatenation
  • Conditional Logic
    • If
    • Else
    • Switch
    • Comparators
    • Concatenate
  • Arrays
    • Unshift
    • Map
    • Spread
    • Shift
    • Pop
    • Join
    • Length
    • Push
    • For Each
    • Sort
    • Indices
  • Loops
    • For
    • While
    • Do...While
  • Functions
    • Higher Order Functions
  • Objects
    • Properties
    • Mutable
    • Reference
    • Prototype
    • Delete
    • Enumeration
    • Global footprint
  • Linked List
    • Add
    • Pop
    • Prepend
    • Shift
  • Browser Object Model (BOM)
    • Window
    • Popup
    • Screen
    • Navigator
    • Cookies
    • History
    • Location
  • Date and Time
  • JSON
  • Error Handling
    • try...catch...finally
  • Events
  • Regular Expression
  • Modules
  • Debugging
  • Classes
    • Static
    • Inheritance
    • Access Modifiers
  • Promise, async/await
    • Async/Await
  • Miscellaneous
    • Hoisting
    • Currying
    • Polyfills and Transpilers
  • Exercises
    • Console
    • Multiplication
    • User Input Variables
    • Constants
    • Concatenation
    • Functions
    • Conditional Statements
    • Objects
    • FizzBuzz Problem
    • Get the Titles!
Powered by GitBook
On this page

Was this helpful?

  1. Miscellaneous

Hoisting

Hosting is a default behavior in JavaScript of moving declarations at the top. While executing a code, it creates a global execution context: creation and execution. In the creation phase, JavaScript moves the variable and function declaration to the top of the page, which is known as hoisting.

// variable hoisting
console.log(counter);
let counter = 1; // throws ReferenceError: Cannot access 'counter' before initialization

Although the counter is present in the heap memory but hasn't been initialized so, it throws an error. This happens because of hoisting, the counter variable is hoisted here.

// function hoisting
const x = 20,
    y = 10;

let result = add(x,y); // ❌ Uncaught ReferenceError: add is not defined
console.log(result);

let add = (x, y) => x + y; 

Here, the add function is hoisted and initialized with undefined in heap memory in the creation phase of the global execution context. Thus, throwing an error.

PreviousMiscellaneousNextCurrying

Last updated 2 years ago

Was this helpful?