What is Hoistin...
What is Hoistin...
Hoisting in JavaScript is a behavior where variable and function declarations are moved to the top of their containing scope during the compilation phase, before the code is executed. This means that variables and functions can be used before they are declared in the code.
In JavaScript, when you declare a variable using the var
keyword, the declaration (but not the initialization) is hoisted to the top of its scope. This means that the variable can be accessed before it is declared, but it will return undefined
until it is initialized.
For example:
console.log(myVar); // Outputs: undefined
var myVar = 5;
console.log(myVar); // Outputs: 5
In this code, the declaration of myVar
is hoisted to the top, but the initialization (myVar = 5
) remains where it is.
Variables declared with let
and const
are also hoisted, but they are not initialized, which means they are in a "temporal dead zone" from the start of the block until the declaration is initialized. Accessing them before the declaration results in a ReferenceError
[1][2][3][4][5][6][7][8][9][10].
Function declarations are also hoisted, which means you can call functions before they are declared in the code. This is because the entire function declaration, including its body, is hoisted to the top of its containing scope.
For example:
hoistedFunction(); // Outputs: "This function has been hoisted."
function hoistedFunction() {
console.log("This function has been hoisted.");
}
Here, hoistedFunction
is available bef...
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào