Java Reference
In-Depth Information
Hoisting is the process of moving a value to the top of the code block where it is used, re-
gardless of where it is defined.
Variable Hoisting
All variable declarations are automatically moved to the top of a function's scope, as if they
were defined at the start of the function. Variable assignment is not hoisted, however. This
means that a variable assigned at the end of the function will have a value of undefined
until the assignment is made. The following example shows how this works:
function hoist(){
console.log(a); // at this point a is undefined
// imagine lots more code here
var a = "Hoist Me!";
console.log(a); // now is a string
At the beginning of the function, the variable a has not been declared or assigned a value,
so in theory, trying to write its value using console.log(a) should result in an error.
Yet the declaration of a is hoisted to the top of the function, so the function knows that a
variable called a exists. The value that it is assigned to is not hoisted, however, so until the
assignment is made, the value of a is undefined .
Hoisting can cause some confusion, so a ninja should declare, and assign if required, all
local variables at the beginning of a function so that hoisting is unnecessary.
Function Hoisting
Functions that are defined inside other functions are also hoisted, but they behave differently
depending on how they are defined.
Search WWH ::

Custom Search