concept global variable in category angular

appears as: global variable, global variables
Getting MEAN with Mongo, Express, Angular, and Node.js 2ED

This is an excerpt from Manning's book Getting MEAN with Mongo, Express, Angular, and Node.js 2ED.

If declaring the global variable in the local scope is wrong, what’s the right way? The rule of thumb is always declare variables in the scope in which they belong. If you need a global variable, you should define it in the global scope, as in the following listing.

Referencing global variables from local scope

You may have noticed that from within the function, the code still references the global variable by using the fully qualified window.fullname. It’s best practice to do this whenever you reference a global variable from a local scope. Again, this practice makes your code easier to come back to and debug, because you can explicitly see which variable is being referenced. The code should look like the following listing.

Listing D.6. Using global variables in local scope
var firstname = 'Simon',
    fullname;
var addSurname = function () {
  var surname = 'Holmes';
  window.fullname = window.firstname + ' ' + surname;      #1
  console.log(window.fullname);                            #1
};
addSurname();
console.log(fullname);
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest