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

7. Scope and Closures > JavaScript Does Not Have Block Scope

JavaScript Does Not Have Block Scope

Since logic statements (e.g., if(){}) and looping statements (e.g., for) do not create a scope, variables can overwrite each other. Examine the code below and make sure you understand that the value of foo is being redefined as the program executes the code.

Live Code

<!DOCTYPE html><html lang="en"><body><script>

var foo = 1; // foo = 1

if (true) {
   foo = 2; // foo = 2
   for(var i = 3; i <= 5; i++) {
       foo = i; // foo = 3,4, then 5
       console.log(foo); // logs 3,4,5
   }
}

</script></body></html>

So foo is changing as the code executes because JavaScript has no block scope—only function, global, or eval scope.


  

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