Typescript variable scope

Author: Dawid Adach

In this lesson, we will cover a different type of variables and scopes.

  1. Replace the content of the onStartup() function:
  2. onStartup(){
      function count(){
        for (var i = 0; i < 9; i++){
        console.log('Counted: ' , i);
  3. And start our application, what you will see?
  4. Function output.

    Note that although our i variable was declared inside a for loop, it is accessible to the console.log() function which is outside of our code block. Why?

    This is because we have declared our variable as var. In JavaScript, all variables declared like that have scope to the nearest function, which in our case is count().

    var variable scope.
  5. Let's change var, to let:
  6. for (let i = 0; i < 10; i++){

    Now the scope of our variable is changed to local:

    let variable scope.
  7. Let's have a look at the error which occurred in line 22 after we change the scope of our variable:
  8. Error.

    and if we save the file, we will see an error in the console during compilation:

    ERROR in src/app/app.component.ts(22,31): error TS2304: Cannot find name 'i'.

    Remember when we talked about compile-time errors? This is a beautiful example, the compiler spots this error and informs us that we are trying to access a variable which isn't accessible within the current scope before we even tried to run our code in a browser. Actually, thanks to Visual Studio we can see an error even before we request the CLI to compile our project. The editor shows us errors in real-time. That's a really awesome feature which will save you a lot of time.

Previous lesson Next lesson

Spread the word:
Do you need help? Use our support forum

About the author

Dawid Adach
For more than 5 years Dawid worked as an IT Consultant specializing in SOA/EAI/ESB in the banking domain. He gained experience working in countries like Netherlands, Belgium, Poland and India developing enterprise-class systems for the most prestigious companies. Since co-founding mdbootstrap.com & brandflow.net in 2016 he has been using and teaching technologies such as Angular, TypeScript, PHP, AJAX, Mongo, SQL, Hadoop Stack, Virtualization, Automation and many others...