Hoisting in JavaScript can be observed in various scenarios involving variables and functions. Let's explore different use cases with both var
and function declarations.
Use Case 1: Variables with var
console.log(name); // Output: undefined
var name = "John";
console.log(name); // Output: John
In this example, the variable name
is hoisted to the top of its scope, allowing us to access it before the actual declaration. However, its value is undefined
until the assignment.
Use Case 2: Function Declarations
sayHello(); // Output: Hello, there!
function sayHello() {
console.log("Hello, there!");
}
Function declarations are hoisted, enabling us to call the function before its declaration in the code. This facilitates cleaner code organization and logical flow.
Use Case 3: Variables with let
and const
console.log(age); // Error: Cannot access 'age' before initialization
let age = 25;
console.log(age); // Output: 25
Unlike var
, variables declared with let
and const
are hoisted but not initialized. Accessing them before initialization results in a ReferenceError.
Use Case 4: Function Expressions
greet(); // Error: greet is not a function
var greet = function() {
console.log("Hello!");
};
Function expressions do not exhibit the same hoisting behavior as function declarations. Accessing them before the declaration results in an error.
Use Case 5: Redeclaration with var
var count = 5;
var count = 10;
console.log(count); // Output: 10
var
allows variable redeclaration within the same scope, and hoisting only considers the first declaration.
Use Case 6: Hoisting within Functions
function example() {
console.log(innerVariable); // Output: undefined
var innerVariable = "I am hoisted!";
console.log(innerVariable); // Output: I am hoisted!
}
example();
Hoisting occurs within function scopes as well. The variable innerVariable
is hoisted within the example
function.
Top comments (0)