Java Reference
In-Depth Information
As
declaration hoisting : This simply means that all variable and
function declarations are moved to the top in their respective
scope. This is the same as saying that you have declared all
variables and functions at the top in the global and function
scopes.
Listing 4-22 shows the same code as in Listing 4-21 but after the declarations are
hoisted. This time, you will not have any problem in understanding the output.
Listing 4-22. Reorganized Code after Declaration Hoisting
// afterhoisting.js
var empId; // Hoisted
function test() {
var empId; // Hoisted
if (empId === undefined) {
empId = 200; // Left after hoisting
}
print("2. empId = " + empId);
}
// Try accessing empId variable before declaring it
print("1. empId = " + empId);
// Declare and initialize empId now
empId = 100; // Left after hoisting
// Call the test function
test();
print("3. empId = " + empId);
1. empId = undefined
2. empId = 200
3. empId = 100
Notice that hoisting occurs for function declarations, not for function expressions,
which enables you to call functions before they are declared. One more thing to
remember: only variable declarations are hoisted, not the assignment part in the variable
declarations, as shown in Listing 4-22.
 
Search WWH ::




Custom Search