After learning how to configure your development environment and how to automatize some of the tasks in your development workflow with Gulp, we will continue our journey towards our goal: becoming a full-stack TypeScript engineer. In this chapter, we will learn some effective usages of some of the core building blocks of the TypeScript programming language: functions and classes. You will learn about the following topics:

  • IIFE immediately invoked function expressions
  • Closures
  • Arrow functions and the polymorphic this operator
  • Access modifiers
  • Local types
  • Abstract classes
  • Mixins
  • Intersection types
  • Class Expressions vs. class Declarations
  • Generics and generic constraints
  • Tag functions and tagged templates
  • Destructuring

3.1 IIFE immediately invoked function expressions

Immediately-Invoked Function Expressions (IIFE) are functions expressions that are instantly invoked after their declaration.

Getting Ready

All you need to use IIFE is an installation of TypeScript 2.0 or higher.

How to do it…

IIFE (also known as self-executing anonymous function) are just like any other function but they are wrapped with parenthesis and invoked immediately after:

(function() {
  // the code here is executed once in its own scope

How it works…

If you warp a variable with parenthesis in a TypeScript or JavaScript statement, the result of executing the statement will be the variable which was wrapped by the parenthesis:

console.log(1, (1)); 
console.log('test', ('test')); 
console.log(true, (true)); 
console.log(new Date().getTime(), (new Date().getTime())); 

The lines of code above log the following in console:

1 1
test test
true true
1448287535398 1448287535398

We can use this little trick to invoke a function after it has been declared:

 (function() { console.log('test'); })

Once the function has been wrapped, we can we can invoke it:

 (function() { console.log('test'); })();

There’s more…

Immediately-invoked function expressions can be used to:

  • Avoid variable hoisting from within blocks
  • Protect against polluting the global
  • Emulate private and static variables.

    Note that it is possible to pass arguments to an IIFE: ts(function(global) { console.log('test'); })(window);

Source Code

IIFE immediately invoked function expressions

See also

Please refer to the recipes about closures and scope in this chapter to learn more about possible applications of Immediately-Invoked Function Expressions (IIFE).

Shiv Kushwaha