Categories
JavaScript Tutorials

Scope of Variables

It is important to note, especially if you have come to JavaScript from another language, that if a variable is defined inside a function, it’s not visible outside of the function. However, a variable defined inside an if or a for code block is visible outside the code block. The term “global variables” describes variables you define outside of any function, as opposed to “local variables” which are defined inside a function. The code inside a function has access to all global variables as well as to its own local variables.

In the next example:

The function f() has access to the variable global. Outside of the function f(), the variable local doesn’t exist.

var global = 1;
function f() {
  var local = 2;
  global++;
  return global;
}
f();
//2
f();
//3
local
//local is not defined

It is also important to note that if you don’t use var to declare a variable, this variable is automatically assigned global scope.

Here’s an interesting example that shows an important aspect of the local versus global scoping.

var a = 123;
function f() {
  alert(a);
  var a = 1;
  alert(a);
}
f();

You might expect that the first alert() will display 123 (the value of the global variable a) and the second will display 1 (the local a). This is not the case. The first alert will show “undefined”. This is because inside the function the local scope is more important than the global scope. So a local variable overwrites any global variable with the same name. At the time of the first alert() a was not yet defined (hence the value undefined) but it still existed in the local space.

Quiz

Click this link for MCQs on scope of variables in functions: MCQs on Scope of Variables