06.07.2017 Views

Mastering JavaScript

Create successful ePaper yourself

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

Chapter 2<br />

Global scope<br />

Any variable that you declare is by default defined in global scope. This is one of<br />

the most annoying language design decisions taken in <strong>JavaScript</strong>. As a global<br />

variable is visible in all other scopes, a global variable can be modified by any scope.<br />

Global variables make it harder to run loosely coupled subprograms in the same<br />

program/module. If the subprograms happen to have global variables that share<br />

the same names, then they will interfere with each other and likely fail, usually<br />

in difficult-to-diagnose ways. This is sometimes known as namespace clash.<br />

We discussed global scope in the previous chapter but let's revisit it briefly to<br />

understand how best to avoid this.<br />

You can create a global variable in two ways:<br />

• The first way is to place a var statement outside any function. Essentially,<br />

any variable declared outside a function is defined in the global scope.<br />

• The second way is to omit the var statement while declaring a variable (also<br />

called implied globals). I think this was designed as a convenience for new<br />

programmers but turned out to be a nightmare. Even within a function<br />

scope, if you omit the var statement while declaring a variable, it's created<br />

by default in the global scope. This is nasty. You should always run your<br />

program against ESLint or JSHint to let them flag such violations. The<br />

following example shows how global scope behaves:<br />

//Global Scope<br />

var a = 1;<br />

function scopeTest() {<br />

console.log(a);<br />

}<br />

scopeTest(); //prints 1<br />

Here we are declaring a variable outside the function and in the global scope. This<br />

variable is available in the scopeTest() function. If you assign a new value to a<br />

global scope variable within a function scope (local), the original value in the global<br />

scope is overwritten:<br />

//Global Scope<br />

var a = 1;<br />

function scopeTest() {<br />

a = 2; //Overwrites global variable 2, you omit 'var'<br />

console.log(a);<br />

}<br />

console.log(a); //prints 1<br />

scopeTest(); //prints 2<br />

console.log(a); //prints 2 (global value is overwritten)<br />

[ 51 ]<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!