TypeScript Variables

A variable is the storage location, which is used to store value/information to be referenced and used by programs. It acts as a container for value in code and must be declared before the use. We can declare a variable by using the var keyword. In TypeScript, the variable follows the same naming rule as of JavaScript variable declaration. These rules are-

  • The variable name must be an alphabet or numeric digits.
  • The variable name cannot start with digits.
  • The variable name cannot contain spaces and special character, except the underscore(_) and the dollar($) sign.

In ES6, we can define variables using let and const keyword. These variables have similar syntax for variable declaration and initialization but differ in scope and usage. In TypeScript, there is always recommended to define a variable using let keyword because it provides the type safety.

The let keyword is similar to var keyword in some respects, and const is an let which prevents prevents re-assignment to a variable.

Variable Declaration

We can declare a variable in one of the four ways:

Declare type and value in a single statement

Syntax #1
var [identifier] : [type-annotation] = value;

Declare type without value. Then the variable will be set to undefined.

Syntax #2
var [identifier] : [type-annotation];

Declare its value without type. Then the variable will be set to any.

Syntax #3
var [identifier] = value;

Declare without value and type.

Then the variable will be set to any and initialized with undefined.

Syntax #4
var [identifier];

Let's understand all the three variable keywords one by one.

var keyword

Generally, var keyword is used to declare a variable in JavaScript.

Example #1
snippet
var x = 50;

We can also declare a variable inside the function:

Example #2
snippet
function a() {
     var msg = " Welcome to rookienerd !! ";
     return msg;
}
a();

We can also access a variable of one function with the other function:

Example #3
snippet
function a() {
    var x = 50;
    return function b() {
         var y = x+5;
         return y;
    }
}
var  b = a();
b();       //returns '55'

Scoping rules

For other language programmers, they are getting some odd scoping rules for var declaration in JavaScript. Variables declared in TypeScript with the var keyword have function scope. This variable has global scope in the function where they are declared. It can also be accessed by any function which shares the same scope.

Example #4
snippet
function f()
{
    var X = 5; //Available globally inside f()
    if(true)
    {
        var Y = 10; //Available globally inside f() 
        console.log(X); //Output 5
        console.log(Y); //Output 10
    }    
    console.log(X); //Output 5
    console.log(Y); //Output 10
}
f();
console.log(X); //Returns undefined because value cannot accesses from outside function
console.log(Y); //Returns undefined because value cannot accesses from outside function
Note
NOTE: As var declarations are accessible anywhere within their containing module, function, global scope, or namespace, some people call this var-scoping or function-scoping. Parameters are also called function scoped.

let declarations

The let keyword is similar to the var keyword. The var declaration has some problems in solving programs, so ES6 introduced let keyword to declare a variable in TypeSript and JavaScript. The let keyword has some restriction in scoping in comparison of the var keyword.

The let keyword can enhance our code readability and decreases the chance of programming error.

The let statement are written as same syntax as the var statement:

Example
snippet
var declaration: var b = 50;
    let declaration: let b = 50;

The key difference between var and let is not in the syntax, but it differs in the semantics. The Variable declared with the let keyword are scoped to the nearest enclosing block which can be smaller than a function block.

Block Scoping

When the variable declared using the let keyword, it uses block scoping or lexical scoping. Unlike variable declared using var keyword whose scopes leak out to their containing function, a block-scoped variable cannot visible outside of its containing block.

Example #1
snippet
function f(input: boolean) {
    let x = 100;
    if (input) {
        // "x" exists here      
        let y = x + 1;
        return y;
    }
    // Error: "y" doesn't exist here
    return y;
}

Here, we have two local variables x and y. Scope of x is limited to the body of the function f() while the scope of y is limited to the containing if statement's block.

Note
NOTE- The variables declared in a try-catch clause also have similar scoping rules. For example:
Example #2
snippet
try {
    throw "Hi!!";
}catch (e) {
    console.log("Hello");
}
// 'e' doesn't exist here, so error will found
console.log(e);
Re-declaration and Shadowing

With the var declaration, it did not matter how many time's we declared variables. We just got only one. In the below example, all declarations of x refer to the same x, which is perfectly valid. But there is some bug, which can be found by the let declaration.

Example without let keyword:

Example
snippet
function f(a) {
    var a;
    var a;
    if (true) {
        var a;
    }
}

Example with let keyword:

Example
snippet
let a = 10;
let a = 20; // it gives error: can't re-declare 'a' in the same scope

Shadowing is the act of introducing a new name in a more nested scope. It declares an identifier which has already been declared in an outer scope. This is not incorrect, but there might be confusion. It will make the outer identifier unavailable inside the loop where the loop variable is shadowing it. It can introduce bugs on its own in the event of accidental Shadowing, as well as it also helps in preventing the application from certain bugs.

Example
snippet
var currencySymbol = "$";
function showMoney(amount) {
  var currencySymbol = "€";
  document.write(currencySymbol + amount);
}
showMoney("100");

The above example has a global variable name that shares the same name as the inner method. The inner variable used only in that function, and all other functions will use the global variable declaration.

The Shadowing is usually avoided in writing of clearer code. While in some scenarios, if there may be fitting to take advantage of it, we should use it with the best judgment.

Hoisting

Hoisting of var

Hoisting is a mechanism of JavaScript. In hoisting, variables and function declarations are moved to the top of their enclosing scope before code execution. We can understand it with the following example.

Note
Note: Hoisting does not happen if we initialize the variable.
Example
snippet
function get(x){   
  console.log(a);  //printing x variable. Value is undefined     
  //declared variable after console hoisted to the top at run time  
  var a = x;      
  //again printing x variable. Value is 3.
  console.log(a);  
}  
get(4);
Output
undefined 4
Hoisting of let

A variable declared with let keyword is not hoisted. If we try to use a let variable before it is declared, then it will result in a ReferenceError.

Example
snippet
{
  //program doesn't know about variable b so it will give me an error.
  console.log(b); // ReferenceError: b is not defined
  let b = 3;
}

const declarations

The const declaration is used to declare permanent value, which cannot be changed later. It has a fixed value. The const declaration follows the same scoping rules as let declaration, but we cannot re-assign any new value to it.

Note
Note: According to the naming standards, the const variable must be declared in capital letters. Naming standards should be followed to maintain the code for the long run.
Example
snippet
function constTest(){
  const VAR = 10;
  console.log("Value is: " +VAR);
}
constTest();
Output
Value is: 10

What will happen when we try to re-assign the const variable?

If we try to re-assign the existing const variable in a code, the code will throw an error. So, we cannot re-assign any new value to an existing const variable.

Example
snippet
function constTest(){
  const VAR = 10;
  console.log("Output: " +VAR);  // Output: 10
  const VAR = 10;
  console.log("Output: " +VAR);  //Uncaught TypeError: Assignment to constant variable
}
constTest();
Output
SyntaxError: Identifier 'VAR' has already been declared.
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +