108k views
1 vote
What is variable hoisting in JavaScript?

A. It refers to the automatic elevation of variable values to the top of the code.
B. It is a process where variables are physically moved to a different memory location.
C. It is a JavaScript feature that allows variables to be used before they are declared.
D. It is a security feature that restricts the use of certain variables in the global scope.

1 Answer

7 votes

Final answer:

Variable hoisting in JavaScript refers to the behavior where variable and function declarations are moved to the top of their containing scope, enabling variables to be used before they are declared.

Step-by-step explanation:

Variable hoisting in JavaScript is C. It is a JavaScript feature that allows variables to be used before they are declared. During the compilation phase, variable and function declarations are moved to the top of their containing scope, which is to the top of the global context or the top of the function scope if they are declared within a function. This means that you can reference variables in your code before they are explicitly defined. However, it's important to note that only the declarations are hoisted, not the initializations. If a variable is referenced before it is initialized, it will result in undefined.

For example:

console.log(myVar); // undefined
var myVar = 5;
console.log(myVar); // 5

In the code above, myVar is hoisted to the top, so it exists when we try to log it the first time, but it doesn't yet have the value that is assigned after the declaration. Hoisting is particularly important to understand for debugging purposes and to avoid reference errors.

User Ppuskar
by
7.8k points