Logesh Paul

UX Designer, Frontend Developer

Scope in Javascript

| Comments

Traditionally, JavaScript only has two types of scope:

1) Global Scope: Variables are known throughout the application, from the moment they are declared onwards

2) Functional Scope: Variables are known within the function they are declared in, from the moment they are declared onwards

The most recent JavaScript specs(ES6) now also allow a third scope:

3) Block Scope: Variables are known within the block they are declared in, from the moment they are declared onwards

How do I create block scope variables?

1
2
var myVariable = "Some text"; // Traditional approach
let myVariable = "Some text"; // Blocked scope

Here is some examples to understand scopes better

A globally-scoped variable

1
2
3
4
5
6
var a = 1;

// global scope
function one() {
  alert(a); // alerts '1'
}

Local scope

1
2
3
4
5
6
7
8
9
10
11
var a = 1;

function two(a) {
  alert(a); // alerts the given argument, not the global value of '1'
}

// local scope again
function three() {
  var a = 3;
  alert(a); // alerts '3'
}

Intermediate: No such thing as block scope in JavaScript (ES5; ES6 introduces let)

1
2
3
4
5
6
7
8
9
var a = 1;

function four() {
  if (true) {
    var a = 4;
  }

  alert(a); // alerts '4', not the global value of '1'
}

Global+Local: An extra complex Case

1
2
3
4
5
6
7
var x = 5;

(function () {
    console.log(x);
    var x = 10;
    console.log(x);
})();

This will print out undefined and 10 rather than 5 and 10 since JavaScript always moves variable declarations (not initializations) to the top of the scope, making the code equivalent to:

1
2
3
4
5
6
7
8
var x = 5;

(function () {
    var x;
    console.log(x); // undefined
    x = 10;
    console.log(x); // 10
})();

Intermediate: Object properties

1
2
3
4
5
6
7
var a = 1;

function five() {
  this.a = 5;
}

alert(new five().a); // alerts '5'

Advanced: Closure

1
2
3
4
5
6
7
8
9
10
11
var a = 1;

var six = (function() {
  var a = 6;

  return function() {
    // JavaScript "closure" means I have access to 'a' in here,
    // because it is defined in the function in which I was defined.
    alert(a); // alerts '6'
  };
})();

Advanced: Prototype-based scope resolution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var a = 1;

function seven() {
  this.a = 7;
}

// [object].prototype.property loses to
// [object].property in the lookup chain. For example...

// Won't get reached, because 'a' is set in the constructor above.
seven.prototype.a = -1;

// Will get reached, even though 'b' is NOT set in the constructor.
seven.prototype.b = 8;

alert(new seven().a); // alerts '7'
alert(new seven().b); // alerts '8'

Comments