Java Reference
In-Depth Information
Consider the code and its output in Listing 4-21. The output will surprise you if you
have not worked with JavaScript before.
Listing 4-21.
Declaration Hoisting in Nashorn
// beforehoisting.js
// Try accessing empId variable before declaring it
print("1. empId = " + empId);
// Declare and initialize empId now
var empId = 100;
function test() {
if (empId === undefined) {
var empId = 200;
}
print("2. empId = " + empId);
}
// Call the test function
test();
print("3. empId = " + empId);
1. empId = undefined
2. empId = 200
3. empId = 100
The first output shows that you can access a variable before declaring it. The variable
value is
undefined
. Inside the
test()
function, you would expect that expression
empId
=== undefined
will read the value of
empId
from the global scope and it will evaluate
to
false
. However, the output shows otherwise. The second output shows that the
if
condition inside the
test()
function evaluated to
true
and the
empId
local variable was
set to 200. The third output shows that the function call did not affect the global variable
empId
and its value remained 100.
You can understand this variable's scoping behavior in two ways:
•
As a
two-phase process
: First, all declarations are processed.
Second, the code is executed. Because all declarations are
processed before executing the code, all variable and function
declarations are available when the code is executed, irrespective
of the place where they were declared. Of course, you need to take
into account the global and function scopes of those declarations.
Search WWH ::
Custom Search