04.11.2015 Views

javascript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 4: Variables, Scope, and Memory<br />

Here, the function add() defines a local variable named sum that contains the result of an addition<br />

operation. This value is returned as the function value, but the variable sum isn ’ t accessible outside the<br />

function. If the var keyword is omitted from this example, sum becomes accessible after add() has been<br />

called, as shown here:<br />

function add(num1, num2) {<br />

sum = num1 + num2;<br />

return sum;<br />

}<br />

var result = add(10, 20); //30<br />

alert(sum); //30<br />

Here, the variable sum is initialized to a value without ever having been declared using var . When<br />

add() is called, sum is created in the global context and continues to exist even after the function has<br />

completed, allowing you to access it later.<br />

Initializing variables without declaring them is a very common mistake in<br />

JavaScript programming and can lead to errors. It ’ s advisable to always declare<br />

variables before initializing them to avoid such issues.<br />

Identifier Lookup<br />

When an identifier is referenced for either reading or writing within a particular context, a search must<br />

take place to determine what identifier it represents. The search starts at the front of the scope chain,<br />

looking for an identifier with the given name. If it finds that identifier name in the local context, then<br />

the search stops and the variable is set; if the search doesn ’ t find the variable name, it continues along<br />

the scope chain. This process continues until the search reaches the global context ’ s variable object. If the<br />

identifier isn ’ t found there, it hasn ’ t been declared.<br />

To better illustrate how identifier lookup occurs, consider the following example:<br />

var color = “blue”;<br />

function getColor(){<br />

return color;<br />

}<br />

alert(getColor()); //”blue”<br />

When the function getColor() is called in this example, the variable color is referenced. At that point,<br />

a two - step search begins. First getColor() ’ s variable object is searched for an identifier named color .<br />

When it isn ’ t found, the search goes to the next variable object (from the global context) and then<br />

searches for an identifier named color . Because that variable object is where the variable is defined, the<br />

search ends. Figure 4 - 5 illustrates this search process.<br />

89

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!