Câu hỏi phỏng vấn Javascript
Câu hỏi

What is Hoistin...

Câu trả lời

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.

Variable Hoisting

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:

javascript Copy
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 Hoisting

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:

javascript Copy
hoistedFunction(); // Outputs: "This function has been hoisted."

function hoistedFunction() {
  console.log("This function has been hoisted.");
}

Here, hoistedFunction is available bef...

senior

senior

Gợi ý câu hỏi phỏng vấn

senior

When would you use import * as X from 'X' ?

senior

What is the new keyword in JavaScript?

entry

What is Scope in JavaScript?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào