Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 2: Javascript Primer > Working with Scope and Closures

WORKING WITH SCOPE AND CLOSURES

When discussing scope it’s important to consider where a variable is defined as well as its lifetime. Where is the variable accessible? In the case of JavaScript, scope is maintained at the function level, not the block level. Hence, variables defined with the keyword var and parameters are visible only inside the function in question.

A nested function has access to its outer function’s variables, except for this and arguments. The mechanism through which a nested function continues to keep the references of its outer function even after the outer function finishes execution is called closure. Closures also help to reduce namespace pollution.

Each time an enclosed function is called, a new scope is created, although the code doesn’t change. The following code shows this behavior.


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint