JavaScript: global and local variables

One of the first concepts you need to grasp in JavaScript is the difference between global and local variables. As a rule of thumb, you should avoid global variables because they pollute the global namespace of your JavaScript code and potentially lead to unexpected problems, not to say that they can generated conflicts between libraries and scripts. I realize that the best tutorial is a tutorial when you can experience a sense of empathy with the author, so here it follows an interesting video tutorial taken from YouTube.

Beside the personal thoughts of the author (humorous smile), the distinction between function scopes is vital. But functions are also objects, so this distinction applies to objects as well. In general, a variable is always visible and accessible inside the context where it's been created. So if you put your variable before any other block, you're using the global context of your script. Conversely, when you create a variable within a block you're actually making it visible only to the members of a local context.

This object:

function Class() {

  var local = 'Private';
  this.property = 'Public';

}

has a private member not because JavaScript supports the traditional OOP concepts related to visibility, but only because the variable local can't be accessed from outside the context where it's been defined. If you want to access it, you have to create a public getter:

function Class() {

  var local = 'Private';
  this.property = 'Public';
  this.getLocal = function() {
    return local;
  }

}

Our getter can access the variable because they both share the same context. Otherwise, the aforementioned variable would not be accessible.

Comments are closed.