2.13 Functions and scope

TypeScript uses lexical scope with function scope. Lexical scoping is defined by Wikipedia as:

Lexical scoping (sometimes known as static scoping is a convention that sets the scope of a variable so that it may only be called (referenced) from within the block of code in which it is defined.

Getting Ready

All you need to be able to use the let and const keywords is an installation of TypeScript version 1.4 or higher.

How to do it…

Consider the following example:
function scope1() { 
  counter = 5; 
  if (true) { 
    var counter; 
  } 
  return counter; 
}

How it works…

The majority of modern programming languages are lexical scoped with block scope. This means that all blocks within the code delimited by the usage of curly brackets ({}) will create a new scope. However, TypeScript uses function scope, this means that a new scope is only created when we use a function. When we invoke the scope1 function we don’t get an error because the variable counter is moved to the top of the scope in a process known as variable hoisting:

scope1(); // 5

The scope is not the if block because TypeScript does not use block scoping. The scope is the scope1 function because TypeScript uses function scope.

There’s more…

In the past, developers used Immediately-Invoked Function Expressions (IIFE) to create a new scope at block level when they needed:

function scope1() { 
  if (true) { 
    var counter = (function(){
		var counter;
		counter = 5; 
		return counter;
	})();
  } 
  return counter; 
}

From TypeScript 1.4, we can use the let and const keywords to have a better control of the scope. The let keyword is used to declare a variable with block scope, so we can re-write the preceding function as:

function scope1() { 
  if (true) { 
    let counter;
	 counter = 5; 
	 return counter;
  }  
}

The const keyword creates a read-only reference to a value. It value is mutable but its variable identifier cannot be reassigned:

const MY_OBJECT = {'key': 'value'};
MY_OBJECT = {'OTHER_KEY': 'value'}; // Error (Reassignment)
MY_OBJECT.key = 'otherValue'; 	 // OK (Mutation)

The let and const keywords can only be used when targeting ES6 with TypeScript 1.4 or higher but TypeScript 1.5 introduces support for the let and const keywords when targeting ES3 and ES5.

Source Code

Functions and scope

See also

Please refer to the next recipe Immediately-Invoked Function Expressions (IIFE) in this chapter to learn more about them.


Shiv Kushwaha

Author/Programmer