TypeScript Variables - TypeScript Tutorial

TypeScript Variables

BLUF: Understanding TypeScript Variables is a fundamental part of building type-safe applications with TypeScript. This tutorial explains the syntax and best practices for implementing this concept reliably.
Type Safety Tip: TypeScript Variables

TypeScript's type system provides early error detection and improved maintainability. Discover how TypeScript Variables enhances your development workflow in the guide below.

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 u nderscore(_) and the dollar($) sign.

In ES6, variables can be declared using the keywords let and const. While these variables share a similar syntax for both declaration and initialization, they differ in terms of scope and application. In TypeScript, it is generally advised to use the let keyword for variable definition, as it offers enhanced type safety.

The let keyword shares similarities with the var keyword in certain aspects, while const is essentially a variant of let that disallows any re-assignment to a variable.

Variable Declaration

A variable can be defined using one of four methods:

  1. Specify the type and value simultaneously in a single declaration.
Example

let [userIdentifier]: [dataType] = newEntry;
  1. Declare a variable without assigning a value. Consequently, the variable will be initialized to undefined.
Example

let [userIdentifier]: [dataType];
  1. Assign a value without specifying its type. Consequently, the variable will be defined as any.
Example

let [item] = data;
  1. Declare without specifying a value or type. Consequently, the variable will be assigned the type any and initialized to undefined.
Example

var [identifier];

Let us examine each of the three variable keywords individually.

var keyword

Typically, the var keyword is employed to define a variable in JavaScript.

Example

var x = 50;

A variable can also be defined within the function:

Example

function greetUser() {
    let greeting = " Hi there, welcome to the TypeScript Tutorial !! ";
    return greeting;
}
greetUser();

It is also possible to access a variable from one function within another function:

Example

function initialize() {
    var initialValue = 70;
    return function compute() {
        var output = initialValue + 7;
        return output;
    }
}
var calculate = initialize();
calculate();  //returns '77'

Scoping rules

Programmers coming from different languages may encounter unusual scoping rules regarding variable declaration in JavaScript. In TypeScript, variables defined using the var keyword possess function scope. Such variables have global visibility within the function in which they are declared. Additionally, they can be accessed by any other functions that are within the same scope.

Example

Example

function sampleFunction()
{
    var initialNumber = 8; //Available throughout sampleFunction
    if(true)
    {
        var additionalNumber = 16; //Available throughout sampleFunction
        console.log(initialNumber); //Displays 8
        console.log(additionalNumber); //Displays 16
    }    
    console.log(initialNumber); //Displays 8
    console.log(additionalNumber); //Displays 16
}
sampleFunction();
console.log(initialNumber); //Results in undefined since value is not accessible outside the function
console.log(additionalNumber); //Results in undefined since value is not accessible outside the function

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 functions similarly to the var keyword. However, the var declaration presents certain issues in programming, which led to the introduction of the let keyword in ES6 for declaring variables in TypeScript and JavaScript. In contrast to the var keyword, the let keyword imposes specific restrictions on scope.

The let keyword can improve the clarity of our code and reduce the likelihood of programming mistakes.

The syntax for let statements is identical to that of var statements:

Example

var initialValue: var updatedB = 75;
let alternateValue: let differentB = 75;

The primary distinction between var and let lies not in the syntax but in their semantics. Variables declared using the let keyword are confined to the nearest surrounding block, which may be smaller than a function block.

Block Scoping

A variable defined with the let keyword employs block scoping or lexical scoping. In contrast to variables declared with the var keyword, which can spill over into their enclosing function's scope, a block-scoped variable remains inaccessible outside of its defining block.

Example

function handleIndicator(isActive: boolean) {
    const total = 200;
    if (isActive) {
        // "output" is initialized in this block
        let output = total + 2;
        return output;
    }
    // Note: "output" is not available in this scope
    return output;
}

In this instance, we define two local variables, x and y. The scope of x is confined to the function f's body, whereas the scope of y is restricted to the block of the enclosing if statement.

NOTE- The variables declared in a try-catch clause also have similar scoping rules. For example:

Example

try {
    throw "Hello!";
} catch (issue) {
    console.log("Welcome Friend");
}
// 'issue' is not defined here, thus an error will occur
console.log(issue);

Re-declaration and Shadowing

Using the var keyword for variable declarations meant that the number of times we declared a variable was irrelevant; we would end up with just one instance. In the example below, every declaration of x points to the same variable x, which is entirely permissible. However, there is an issue that can be identified when using the let keyword for declarations.

Example without let keyword:

Example

function sample(argument) {
    var tempVariable;
    var additionalVariable;
    if (true) {
        var innerVariable;
    }
}

Example with let keyword:

Example

let initialValue = 15;
let secondaryValue = 25; // Error occurs: 'secondaryValue' cannot be redeclared in the same scope

Shadowing refers to the process of introducing a new identifier within a more nested scope, which has already been defined in an outer scope. While this practice is not inherently wrong, it can lead to confusion. The outer identifier becomes inaccessible within the loop where the loop variable is shadowing it. This can potentially introduce errors due to unintentional shadowing, but it can also assist in safeguarding the application against specific bugs.

Example

Example

let currencySymbol = "€";
function showFunds(amount) {
  let nationalCurrency = "¥";
  document.write(nationalCurrency + amount);
}
showFunds("300");

In the example provided, a global variable is defined with the same name as that of the inner method. The inner variable is utilized solely within that specific function, while all other functions will reference the global variable declaration.

In coding, shadowing is generally discouraged to promote greater clarity. However, in certain situations where it may be appropriate to utilize it, we should apply it judiciously.

Hoisting

Hoisting of var

Hoisting is a feature of JavaScript. In this process, variable and function declarations are relocated to the top of their respective scope prior to the execution of the code. This can be illustrated through the following example.

Note: Hoisting does not happen if we initialize the variable.

Example

Example

function show(output){   
  console.log(holder);  //displaying output variable. Current output is undefined     
  //variable declaration happens later in execution because of hoisting  
  var holder = output;      
  //displaying output variable again. Now it's 5.
  console.log(holder);  
}  
show(6);

Output:

Output

undefined  
5

Hoisting of let

A variable that is declared using the let keyword does not undergo hoisting. Attempting to access a let variable prior to its declaration will lead to a ReferenceError.

Example

Example

{
  // The program does not recognize variable number, resulting in an error.
  console.log(number); // ReferenceError: number is not defined
  let number = 10;
}

const declarations

The const keyword is utilized to declare an immutable value that cannot be altered subsequently. It maintains a constant value. The const declaration adheres to the same scoping principles as the let declaration; however, it does not permit re-assignment of a new value.

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

Example

function constantExample() {
  const VALUE = 20;
  console.log("The output is: " + VALUE);
}
constantExample();

Output:

Output

The output is: 20

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

Attempting to reassign a previously defined const variable in code will result in an error. Therefore, it is not possible to assign a new value to an already established const variable.

Example

Example

function constantExample() {
  const VALUE = 30;
  console.log("Output: " + VALUE);  // Output: 30
  const VALUE = 30;
  console.log("Output: " + VALUE);  //Uncaught TypeError: Assignment to constant vari```
let userIdentifier = "Alice";
let userIdentifier = "Emma"; // This will cause a reference error

console.log(userIdentifier);

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience