04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

window<br />

2<br />

color<br />

getColor<br />

1<br />

return color<br />

Figure 4 - 5<br />

Given this search process, referencing local variables automatically stops the search from going into<br />

another variable object. This means that identifiers in a parent context cannot be referenced if an<br />

identifier in the local context has the same name, as in this example:<br />

var color = “blue”;<br />

function getColor(){<br />

var color = “red”;<br />

return color;<br />

}<br />

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

In this modified code, a local variable named color is declared inside the getColor() function. When<br />

the function is called, the variable is declared. When the second line of the function is executed, it<br />

knows that a variable named color must be used. The search begins in the local context, where it finds<br />

a variable named color with a value of ” red ” . Because the variable was found, the search stops and<br />

the local variable is used, meaning that the function returns ” red ” . Any lines of code appearing after the<br />

declaration of color as a local variable cannot access the global color variable.<br />

Variable lookup doesn ’ t come without a price. It ’ s faster to access local variables<br />

than global variables because there ’ s no search up the scope chain.<br />

Garbage Collection<br />

JavaScript is a garbage - collected language, meaning that the execution environment is responsible for<br />

managing the memory required during code execution. In languages like C and C++, keeping track of<br />

memory usage is a principle concern and the source of many issues for developers. JavaScript frees<br />

developers from worrying about memory management by automatically allocating what is needed and<br />

90

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

Saved successfully!

Ooh no, something went wrong!