TypeScript Lesson 2 - Variable Declations

Share:
We can declare the variable in TypeScript in three ways, i.e using, let, var and const keywords. let is similar to var in some aspects but its avoid some of the common mistakes that users do in JavaScript. const types are the constant values which prevent re-assignment to the variable.

Here we are elaborating each one more briefly. If you are familiar with these keywords then you can skip this lesson.

var declaration

This is the traditional way of declaring a variable.

var age = 27;
var name = "John";
In the above example, we just declared two variable v1 and v2 with the value 100 and "John" respectively.

We can also declare a variable inside a function:

function f1() {
    var message = "Hello, My name is John!";
    return message;
}
and we can also access those same variables within other functions:

function f() {
    var a = 10000;
    return function f1() {
        var b = a + 1;
        return b;
    }
}

var f1 = f();
f1(); // output '10001'

We can declare a variable to multiple times by var keyword within the same block of code.
For example below code will run without any error:

function f(flag) {
 var value = 121; //First Initialization -- No Error
 .
 .
 .
 var value = "Hello"; //Second Initialization - No Error
 if(flag){
  var value = 1212.12;//Third Initialization - No Error
 }
}

By var keyword we can define a variable inside a block of code and can use it outside of the scope without any error:

function f(flag){

 if(flag){
  var value = "Hello, World!";
 }
 
 return value;
}
console.log(f(true)); //Will print "Hello, World!"
console.log(f(false)); //Will print "Undefined"

let declaration

Now we know var has some problems, which is overcome the let keyword, Apart from the keyword used, let declaration also written in the same way as var declaration are.

For example
let hello  = "Hello World!";.
We can't declare a variable to multiple times by let keyword within the same block of code.

For example below code will through error in same block:

function f(flag) {
 var value = 121; //First Initialization -- No Error
 .
 .
 .
 var value = "Hello"; //Second Initialization - Will through error
 if(flag){
  var value = 1212.12;
  //Third Initialization - No Error (Has another block scope)
 }
}

Unlike var, the let statement has the block-scope, That means it doesn't allow to access the variable to outside of the block scope.

function f(flag){

 if(flag){
  var value = "Hello, World!";
 }
 
 return value; //will through error
}

const declaration

Another way of declarations variables is by using const keyword.

var maxNumberOfLiveUsers = 100;

The const keyword is similar to let but with a a difference, i.e. it prevents its variables to re-assign the value, It cannot be changed
after the initialization.


var maxNumberOfLiveUsers = 100;
.
.
maxNumberOfLiveUsers = 50; //Error

No comments

Post your comment.