Make Mobile Apps with Ionic Framework 3 - Tutorial Part 4 #Variable Declaring in TypeScript

in #developer9 years ago (edited)

0.jpg
In Typescript, there are two ways to declare a variable. You can use the “var” keyword which you have seen in Javascript.

var count = 10;

Or we can use the “let” keyword.

let count = 10;

Before explain the different I need to clarify that the let keyword is also being added to the Javascript. Javacript has different versions. We have ES5 (EcmaScript 5) which is the version of Javascript supported by all browsers. It’s been around for a long time.

Now we have ES6 which is the newer version and it was introduced in 2015. And from that point the Ecmascript team which is the team extending Javascript decided to use year number instead of the version number. So we have ES6 (ES2015), ES2016 and ES2017. The ES2015 have the “let” keyword.

Let me explain how it’s works. So I’m gonna define a function named steemIt.

function steemIt() {

}

I’m gona define a for loop block.

function steemIt() {
    for (var i = 0; i < 10; i++) {
        console.log(i);
    }
}

Declaring “i” to 0. And as long as i less than 10 let’s incrementing. Then log i’s value into console. Then end of this function, log i’s final value into the console. And call this function.

function steemIt() {
    for (var i = 0; i < 10; i++) {
        console.log(i);
    }
    console.log(“Final i is:” + i);
}

steemIt();

I’m gonna compile this file in terminal. And execute with node.js.

1.png

Now we have value of i at the end is 10. This is the issue we have when declaring a variable with var keyword. We have the declare i in for block but is also meaningful and available outside the for block. If you had work with languages like Java or C# you know that we don’t have this concept in those languages.

In Javascript a variable declared with the var keyword scope to the nearest function (in our example; steemIt function). So once we declared i in for block it’s available anywhere in this function.

Now let’s we what happened when we declare this variable with “let” keyword.

2.png

We immediately got red underline in i variable which outside the for block. If we compile this Typescript file, we got a compilation error. Like;

tsc hello-steem.ts
hello-steem.ts(5,30): error TS2304: Cannot find name 'i'.

This is one of the beauties of Typescript. When you are writing Typescript code, you can catch this errors at compile time, before you run application. Before you’re deployed.

TO-DO:
Please compile the valid Typescript code. In code, use the “var” and “let” keyword. Then review the differences in hello-steem.ts and hello-steem.js files.

Previous Chapter: Installing Typescript

Previous Chapter: Types and Type Annotation in TypeScript

Coin Marketplace

STEEM 0.04
TRX 0.33
JST 0.081
BTC 60992.07
ETH 1619.89
USDT 1.00
SBD 0.42