Typescript variable scope

Author: Dawid Adach

-

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

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

    Note that although our i variable was declared inside a for loop, it is accessible for console.log() function which is outside of for 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 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, compiler spots this error and informs us that we are trying to access a variable which isn't accessible within 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 CLI to compile our project. The editor shows us errors in a real-time, that's a really awesome feature which will save you a lot of time.


Next lesson

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

About author

Dawid Adach
For more than 5 years Dawid was working as an IT Consultant specializing in SOA/EAI/ESB for banking domain. He was gaining experience working in countries like Netherlands, Belgium, Poland and India developing enterprise-class systems for the biggest companies within a domain. Since 2 years as a co-founder of mdbootstrap.com & brandflow.net is using and teaching others technologies like Angular, TypeScript, PHP, AJAX, Mongo, SQL, Hadoop Stack, Virtualization, Automation and many others...
Sign up to follow your progress and get additional benefits