Understanding Scope in JavaScript Part 1

Understanding Scope in JavaScript Part 1

·

3 min read

Scope are a set of rules that instruct the engine to lookup variables by its identifier. To understand scope you have got to think in terms of conversion.

Types of Scope

  • Lexical Scope
  • Dynamic Scope

Lexical scope is the most commonly used by numerous programming languages, which JavaScript is not an exception. Lexical scope is based on how the variables and functions are written. To best understand scope in JavaScript, lets consider this simple example:

function foo(a) {                             
    var b = a * 2;                              
    function bar(c) {                    
        console.log(a, b, c);
    }
    bar (b * 3);
}
foo(3);  // 3, 6, 9

This is an example of a nested scope, this means a block of function is nested into another function. There are three scope in the example above. Think of these scopes as containers inside other containers.

  • Scope 1 contains one identifier which is foo.
  • Scope 2 contains the scope 1 and its its three identifiers namely a, b, and bar.
  • Scope 3 is nested inside scope bar and it contains only one identifier namely c.

These scopes are defined where the block of the code is written, this is why they are referred as lexical scope.

function foo(a) {                                 
    var b = a * 2;                         
    function bar(c) {            
        console.log(a, b, c);
    }
}
bar (b * 3); Reference error
foo(3);

You would get an uncaught Reference error: bar not defined if you call the bar function outside the foo scope. To avoid reference error of this nature, it is good to understand how to define variables and call them within the inner or globe scope as at when convenient.