javascript core : Hoisting
Hoisting in JavaScript is like setting up placeholders for your variables and functions, allowing you to use them before you've actually declared them in your code. It's as if JavaScript moves all your declarations to the top, so they're ready to be used anywhere in your code, even if you haven't written them yet. This works clearly for functions and somewhat differently for variables, where variables declared with var
are hoisted but initially set to undefined
until their actual declaration is reached in the code.
example: variable hoisting
console.log(myVar); // Output: undefined (undefined/not defined are different)
var myVar = 5;
console.log(myVar); // Output: 5
// Attempt to log 'myVar' to the console before it's explicitly defined.
// Due to variable hoisting, 'myVar' is known but its value is not set, resulting in 'undefined'.
console.log(myVar); // Output: undefined
// Declare and initialize 'myVar' with the value of 5.
// The declaration part is hoisted to the top, but the initialization happens here.
var myVar = 5;
// Now that 'myVar' has been initialized, logging it to the console will show its value.
console.log(myVar); // Output: 5
function hoisting
sayHello(); // Output: "Hello, world!"
function sayHello() {
console.log("Hello, world!");
}
Here, we call the sayHello function before it's defined. Thanks to hoisting, this works without any errors because the function declaration is hoisted to the top of its scope. This behavior allows us to call functions before they appear in the code.
Example 3: Limitations of Hoisting with let and const
sayHi(); // TypeError: sayHi is not a function
var sayHi = function() {
console.log("Hi!");
};
// Attempt to call 'sayHi' before it's defined. This results in a TypeError because at this point, 'sayHi' is undefined.
// This is due to the fact that function expressions are not hoisted like function declarations.
sayHi(); // TypeError: sayHi is not a function
// Define 'sayHi' as a function expression. Unlike function declarations, the variable 'sayHi' is hoisted but its assignment as a function happens at runtime.
var sayHi = function() {
console.log("Hi!");
};
// If 'sayHi()' were called here, after its definition, it would successfully log "Hi!" to the console.
coclusion:
Hoisting is a fundamental concept in JavaScript that can lead to some interesting behavior. By understanding how hoisting works, developers can avoid potential pitfalls and write more predictable code. Remember, function declarations are fully hoisted, but variable declarations are only partially hoisted, and the initialization stays in place. Keep these nuances in mind, and you'll navigate the quirks of JavaScript hoisting with ease
next would be difference between undefined and not defined