Posts

Showing posts with the label hoisting

The Concept of Hoisting in JavaScript

Hoisting is a unique behavior in JavaScript where declarations of functions, variables, and classes appear to move to the top of their scope before any code is executed. This means you can use them even before they are declared in your code, leading to some interesting and sometimes confusing situations. Here's a breakdown of how hoisting works for different types of declarations: 1. Function Declarations: Function declarations are fully hoisted . This means the entire function definition, including its name, arguments, and body, is moved to the top of its scope. You can call a function before it's declared in your code. JavaScript // This will work correctly! myFunction(); function myFunction () {   console .log( "I am hoisted!" ); } 2. Variable Declarations with var: var declarations are partially hoisted . While the variable declaration itself is moved to the top of its scope, its value assignment remains where it is written . Therefore, accessing the variable be