Javascript: Understanding Global and Local Scope

How and where you declare a variable determines how and where your program can make use of that variable. This concept is called variable scope. JavaScript has two types of scope:

  • Global variables can be used anywhere inside of a program.
  • Local (function) variables are variables that you create inside of a protected program within a program, called a function.
In below example, the programmer wants to have a variable called movie that is global, and a separate variable with the same name that is only valid within the function called showBadMovie. This is a perfectly normal thing to do, and under normal circumstances, the movie variable inside the function wouldn’t affect the global variable. However, if you forget to use the var keyword when declaring the movie variable inside the function, bad things happen.

var movie = "The Godfather";

function showGoodMovie () {
  alert (movie + " is a good movie!");
}

function showBadMovie () {
  movie = "Speed 2: Cruise Control";
  alert (movie + " is a bad movie!");
}


Notice that the var keyword is missing from before the movie variable in showBadMovie(). JavaScript assumes that you want to override the global movie variable, rather than create a local function variable. The results are positively disastrous!

showGoodMovie(); // pops up "The Godfather is a good movie!"

showBadMovie(); // pops up "Speed 2: Cruise Control is a bad movie!"


/* Oh no! The global variable is now Speed 2: Cruise Control, not the good movie name anymore! */

showGoodMovie(); // pops up "Speed 2: Cruise Control is a good movie!"

No comments:

Post a Comment