Skip to content


Share This:

  • LET
    – block scoping
    – Accessing a let-declared variable earlier than its let.. declaration/initialization causes an error, whereas with var declarations the ordering doesn’t matter (except
    – This ReferenceError from accessing too-early let -declared references is technically called a TDZ (temporal dead zone) error

if (typeof a === "undefined") {
console.log( "cool" );
if (typeof b === "undefined") {
// ..
// ReferenceError!
// ..
let b;

  • let + for
    – The let i in the for header declares an i not just for the for loop itself, but it redec‐
    lares a new i for each iteration of the loop. That means that closures created inside
    the loop iteration close over those per-iteration variables the way you’d expect.

var funcs = [];
for (let i = 0; i < 5; i++) {
funcs.push( function(){
console.log( i );
} );
// 3

var funcs = [];
for (var i = 0; i < 5; i++) {
let j = i;
funcs.push( function(){
console.log( j );
} );
// 3

  •  Const
    – immutable value
    – but object inside it can be changed.
    – When we say “`const` variables are immutable” it only means that the variable always has to point to the same thing. It does not mean than the thing it points to can’t change over time.
    – If we want the value of foo to be immutable we have to freeze it using Object.freeze(… ) .

'use strict';
/* // Declaring a const variable
const foo; // SyntaxError: Missing initializer in const declaration
/* // Declaring a const variable
const moo = 1;
moo = 2; // TypeError: `foo` is read-only
/* // Block Scoping
function func() {
if (true) {
const tmp = 123;
console.log(tmp); // Uncaught ReferenceError: tmp is not defined
*/const foo = Object.freeze({});
foo.prop = 1;

  • Block Scope
  • Immutable var
  • Multiline String
  • Variable Substitution

    let name = "asim";
    let multi = `
  •  Fat Arrow Functions

    setTimeout(function() {
    console.log("setTimeout called!");
    }, 1000);

setTimeout(() => console.log("setTimeout called!"), 1000);

let add = function(a,b) {
return a + b;

let add = (a,b) => a + b;//fat arrow syntax if it is on one line, the statement gets returned automatically without the need to use the return keyword.

  • Destructuring

–  Destructuring is a way of extracting values into variables from data stored in objects and arrays.

  1. Object Destructuring
    const obj = {first: 'Asim', last: 'Hussain', age: 39 };

const f = obj.first;
const l = obj.last;
console.log(f); // Asim
console.log(l); // Hussain

const {first: f, last: l} = obj;
console.log(f); // Asim
console.log(l); // Hussain


  • {first: f, last: l} describes a pattern , a set of rules for how we want to
    destructure an object.

// {prop} is short for {prop: prop}
const {first, last} = obj;
console.log(first); // Asim
console.log(last); // Hussain

2. Array Destructuring

-Array destructuring works in a similar way except it extracts based of the index in
the array, like so:

const arr = ['a', 'b'];
const [x, y] = arr;
console.log(x); // a
console.log(y); // b


3. Function Parameter Destructuring

  • One really useful use case for destructuring is in function parameters.

function f(options) {
f({x:1}); // 1

Now we can define the function parameter list as an object destructure pattern , like
so:function f({x}) {
console.log(x); // Refer to x directly

  • Notice that in the function body above we can refer to x directly, we don’t have to
    refer to it through an object property like options.x .


  • For & ForEach

  • For In

    – The for-in loop is designed for iterating over an objects properties ,

var obj = {a:1,b:2};
for (let prop in obj) {
// a
// b

  • Promise API

    • In ES6 we have an alternative mechanism built into the language called a promise .
      A promise is a placeholder for a future value.
      It serves the same function as callbacks but has a nicer syntax and makes it easier to
      handle errors.
    • Immediate Resolution or Rejection
    • Chaining
    • Promises pass an error along the chain till it finds an error handler. So we don’t
      need to define an error handler for each then function, we can just add one at the
    • Catch


  • Object Orientation in JavaScript

    • We normally call the way object orientation is implemented in C++ or Java as the
      Classical OO Pattern and the way it’s implemented in JavaScript as the Prototype
      Pattern .
    • So in ES6 we have an alternative syntax, one that closer matches the classical object
      orientated pattern as is seen in other languages.


  • Class

    • A class is a blueprint for creating objects with specific functions and properties
      already attached to it.
    • A class is a blueprint for creating an object, we call that created object an instance of
      a class , or a class instance or just instance for short.
  • Inheritance

    • A class can inherit from another class. We can create a class blue-print that extends
      an existing class blue-print by adding other methods or properties.
    • by using the extends keyword


class Person { 1
firstName = ""; 2
lastName = "";
constructor(firstName, lastName) { 3
this.firstName = firstName;
this.lastName = lastName;
name() { 4
return `${this.firstName} ${this.lastName}`;
whoAreYou() {
return `Hi i'm ${}`; 5


1 We define a class using then class keyword.
2 We describe the properties we want on our class instance.
3 Each class has a special constructor function, this is called when we create an instance of a class with new
4 We describe the functions, also known as methods, that we want on our class instance.5 this in a method points to the class instance, the object that is created using this class.
5 this in a method points to the class instance, the object that is created using this class.


let asim = new Person("Asim","Hussain");
// "Hi i'm Asim Hussain"

class Student extends Person { 1
course; 2
constructor(firstName, lastName, course) {
super(firstName, lastName); 3
this.course = course;
whoAreYou() {
return `${super.whoAreYou()} and i’m studying ${this.course}`; 5

let asim = new Student("Asim", "Hussain", "Angular 2");
// Hi i'm Asim Hussain and i'm studying Angular 2

1 We use the extends keyword to signal that this class inherits all the properties and methods from the parent
Person class.
2 We can describe additional properties.
3 We use the super function to call the constructor of the parent class
4 We can override member functions of the parent class with our own versions.
5 In member functions super refers to the parent instance.


  • Access Modifiers

    • TypeScript adds some nice functionality on top of ES6 classes, namely
      function and property visibility via access modifiers .
    • public
      This is the default and means its visible everywhere.
      Only member functions of the class it’s declared in can see this.
      Only the class it’s declared in and any class that inherits from that class can see
  • Interfaces

    • An interface can be used in a number of scenarios but by far the most common is when used with classes.

class Person implements Human {


  • Human in the example above is an interface . An interface lets you describe the minimum set of public facing properties or methods that a class has.
  • Another way interfaces are explained is that they describe a set of rules the class has to follow, a contract it has to adhere to.

interface Human {
firstName: string;
lastName: string;


  • Since interfaces are all about the public interface of a class they can’t have access modifiers, the properties above have to be public .
  • error TS2420: Class ‘Person’ incorrectly implements interface ‘Human’. Property ‘firstName’ is missing in type
  • Sometimes however we might want an interface to describe an optional contract. We can append ? to the name of the property or function to mark it as optional


interface Human {
firstName: string;
lastName: string;
name?: Function;
isLate?(time: Date): Function;



  • Decorators

    • This is a new feature that will probably make it into the ES7 version of JavaScript, it’s
      not available right now however even in the ES6 version.
    • It allows us to decorate classes and functions, similar to annotations in java and
      decorators in python.
    • @course is just a function
    • The first argument to the course function is the target .
    • This is the thing the decorator is attached to, so for a class it’s going to be the function
      constructor for that class
    • With decorators we can configure and customise our classes at design time.
    • They are just functions that can be used to add meta-data, properties or functions to
      the thing they are attached to.


function Student(config) {
return function (target) {
Object.defineProperty(target.prototype, 'course', {value: () => config.course})

function Std(config) {
return function (target) {
Object.defineProperty(target.prototype, ‘cp’, {value: () => config.cp})

course: “angular3”

class Person {
constructor(private firstName, private lastName) {

public name() {
return `${this.firstName} ${this.lastName}`;

protected whoAreYou() {
return `Hi i’m ${}`;
cp: “test”
class Person1 {
constructor(private firstName, private lastName) {

public name() {
return `${this.firstName} ${this.lastName}`;

protected whoAreYou() {
return `Hi i’m ${}`;

let asim = new Person(“Asim”, “Hussain”);
//noinspection TypeScriptUnresolvedFunction


  • Modules

    • Module Loading
        • By default javascript doesn’t have a module system like other languages, e.g. Java or
        • This means that if you wanted to call a function in some other file, you have to
          remember to explicitly load that file via script tags before you call the function.
        • If you tried to use code that you forgot to add via a script tag, then javascript would

      import foo from bar;

    • The language itself figured out where bar was, loaded it up from the filesystem,
      extracted the function foo and made it available to you in your file to use.
    • This feature was missing in JavaScript so the community developed their own
      solutions, such as CommonJS which is used in node.
  • ES6 Modules

    • ES6 took the best of the existing module systems and introduced this concept on a
      language level.
    • Although it’s made it into the ES6 standard it’s up to the javascript engine makers to
      actually implement it natively and they haven’t … yet .
    • So until that happens we code using the ES6 module syntax in TypeScript. When
      typescript transpiles the code to ES5 it uses the CommonJS module loading system
      which we touched on above.
    • We can configure TypeScript to use other module loaders, but the default is CommonJS.
  • Exporting & Imoporting

  • Types

    • Transpile-time type checking

      • Some of the most common mistakes we make while writing JavaScript code is to
        misspell a property or a method name.
      • We only find out about the mistake when we get a runtime error , that is to say when
        we are running our application.
      • TypeScripts transpilation mechanism also performs type checking , however it only
        works when we tell TypeScript the type of things.
      • let a: number = 1; a = “1”; //error TS2322: Type ‘string’ is not assignable to type ‘number’.
      • Basic Types, Arrays, Functions, Enum(ES6),  Class & Interface, Any, Void
    • Type Assertion
        • Sometimes we end up in a situation where we know more than TypeScript about the
          type of something. In those situations we can use type assertions as a hint to the
          transpiler about the type of something, like so:
        • (<string>value) lets TypeScript know that we believe the type of value to be string.

      let value: any = "Asim Hussain";
      let length: number = (<string>value).length;

    • Generics
        • With generics we can dynamically generate a new type by passing into the Post type
          a type variable , like so:

      class Post<T> {
      content: T;
      let videoPost: Post<Video>

  • noImplicitAny flag in tsconfig.json

    • set to true then TypeScript throws an error if no type is present.
  • Types for external libraries

    • if you wanted to use code that wasn’t written in TypeScript or which you are
      not going to include as TypeScript and compile yourself.
    • We can use something called an ambient type definition .
    • This is a file that contains meta-data about the types in another library, a meta-type
    • This repository ( ) contains type
      definitions for some of the most popular 3rd party javascript libraries.
    • To use them in a file we simply:-
      • 1. Download the associated type file, for example jquery.d.ts .
      • 2. In the typescript file where we want to use the 3rd party library, add this to the
        top of the file:
        /// <reference path=”jquery.d.ts” />
  • typings
    • Thats a bit cumbersome so there is also a command line tool you can use called
      typings which handles the leg-work for you.
    • We install it via npm , like so:
      npm install -g typings
    • In our project folder we then initialise a config file by typing typings init this creates a typings.json file.
    • Then we can install type definition files like so:
      typings install jquery --save --source dt --global
    • This downloads and installs the type definition files to the ./typings folder and conveniently bundles all of the downloaded files into a single file called index.d.ts .
    • So then to use jQuery with typescript type support we just need to add a reference to index.d.ts to the top the file where we use jQuery.
      /// <reference path="./typings/index.d.ts"/>

Leave a Comment

Your email address will not be published. Required fields are marked *