Explain what is Hoi...
Explain what is Hoi...
Hoisting in JavaScript is a behavior where the JavaScript interpreter appears to move the declaration of variables, functions, and sometimes classes to the top of their containing scope before code execution begins. This behavior allows variables and functions to be used before they are formally declared in the script, leading to some unique effects and potential pitfalls in JavaScript programming.
When it comes to variables, hoisting depends on how the variable is declared:
var
: Variables declared with var
are hoisted to the top of their functional or global scope. The declaration is hoisted, but the initialization is not. If you try to use a var
-declared variable before it is initialized, it will result in undefined
because only the declaration (var x;
) is hoisted, not the initialization (x = value;
)[1][2][3][4][5][6].
console.log(x); // Outputs 'undefined' because the declaration 'var x;' is hoisted
var x = 5;
let
and const
: Unlike var
, variables declared with let
and const
are also hoisted to the top of their block scope, but they are not initialized. Accessing them before the declaration results in a ReferenceError
due to the "temporal dead zone," a state where the variables exist but cannot be accessed until the declaration is evaluated[1][2][3][4][5][6].
console.log(y); // Throws ReferenceError: y is not defined
let y = 5;
Function hoisting allows functions to be called before they are declared in the code. This only applies to function declarations, not function expressions.
Function Declarations: These are hoisted to the top of their containing scope, allowing them to be called before they are defined in the code[1][2][3][4].
hoistedFunction(); // Outp...
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào