Variable in TypeScript

Variable in TypeScript

16 Oct 2024
Intermediate
231K Views
8 min read
Learn with an interactive course and practical hands-on labs

TypeScript Programming Course

Understanding Variables in TypeScript

Variables in TypeScript...! You might be familiar with variables from other programming languages, but In TypeScript variable provides several additional capabilities that help you write safer and more maintainable code. So what precisely are variables? Simply speaking, they are containers for holding data values, such as numbers, texts, or even more complicated structures. TypeScript provides several ways to define these variables, including let, const, and var, each with its own distinct behavior and scope.

So in this TypeScript Tutorial, We are gonna explore Variables in TypeScript including its types and examples.

What Are Variables?

Variables are containers that hold data values. In TypeScript, you can think of them as named pointers to a memory region containing a specific value. A variable's value can change during the execution of a program.1

Declaring Variables in TypeScript

In TypeScript, variables can be declared using three keywords: let, const, and var. Each keyword has its own scope and behavior.

1. let

The let keyword allows you to declare block-scoped variables. This means that the variable is only accessible within the block in which it was defined (such as within a function or an if statement).

let x: number = 10;
if (true) {
    let x: number = 20; // Different x
    console.log(x); // Output: 20
}
console.log(x); // Output: 10

In this example, the first x is defined outside the block and retains its value, while the x inside the block shadows the outer variable.

2. const

The const keyword is used to declare variables that are read-only, meaning their values cannot be reassigned after their initial definition. Similar to let, const variables are block-scoped.

const PI: number = 3.14;
// PI = 3.14159; // This will cause an error: Cannot assign to 'PI'
console.log(PI); // Output: 3.14

Here, attempting to reassign a new value to PI will result in a compile-time error.

3. var

The var keyword declares variables that are function-scoped or globally scoped, which can lead to unexpected behaviors due to hoisting. Hoisting means that variable declarations are moved to the top of their containing scope during compilation.

function example() {
    if (true) {
        var y: number = 30; // y is function-scoped
    }
    console.log(y); // Output: 30
}
example();

In this case, the variable y is accessible outside the if block because it is function-scoped.

Types of Variables

TypeScript supports various types of variables, allowing developers to specify the type of data a variable can hold. This feature provides better type safety and enables the TypeScript compiler to catch potential errors.

1. Basic Types

Some of the basic types include:

  • Number: Represents numeric values (both integers and floating-point).
    let age: number = 25;
  • String: Represents textual data.
    let name: string = "John Doe";
  • Boolean: Represents a value that can be either true or false.
    let isStudent: boolean = true;

2. 3Arrays and Tuples

You can also declare arrays and tuples in TypeScript:

  • Array: Represents a collection of items of the same type.
    let numbers: number[] = [1, 2, 3, 4];
  • Tuple: Represents an array with fixed sizes and known data types for each index.
    let user: [string, number] = ["Alice", 30];

3. Enums

Enums allow you to define a set of named constants, providing a way to work with a set of related values.

enum Direction {
    Up,
    Down,
    Left,
    Right,
}

let move: Direction = Direction.Up; // move will be 0

Best Practices for Using Variables

  1. Use const by Default: Unless you know the value of a variable needs to change, use const to promote immutability. This helps prevent accidental changes to variables.
  2. Limit Scope with let: Use let for variables that may change, and keep their scope as narrow as possible. This enhances readability and maintainability.
  3. Type Annotations: Always provide type annotations for better type safety. This will help you catch errors early during development.
  4. Avoid var: Prefer using let and const over var to avoid hoisting issues and unexpected behaviors.
  5. Descriptive Names: Use meaningful variable names to make your code self-documenting. For example, use studentCount instead of x or y.

Variable Statement

In TypeScript, a variable statement is extended to include optional type annotations.

Syntax

  :  = ; 
  : ;

1. Block Scoping

let supports block scope. When you define, a variable using let within a block like if statement, for loop, switch statement, etc., the block-scoped variable is not visible outside of its containing block.

block.js

function foo(flag: boolean) {
 let a = 100;
 
 //if block
 if (flag) { 
 // 'a' exists here
 let b = a + 1;
 return b;
 }
 // Error: 'b' doesn't exist here
 return b;
}

2. Hoisting

When you use var to declare a variable, you have to deal with hoisting. Hoisting is JavaScript's default behavior of moving variable declarations to the top of the current scope (i.e. top of the current js file or the current function). It means, in JavaScript, a variable can be used before it has been declared.

hoisting.js

var x = "Gurukulsight";
function foo() { 
 console.log(x); //Gurukulsight
}

function bar() {
 console.log(x); //undefined
 var x; //x declaration is hoisted, that’s why x is undefined
}
foo();
bar();

In the above bar function declaration of the x variable will move to the top of the bar function variable declaration and within the bar function, we have not specified any value to x, hence its default value is undefined.

Important Information

  1. JavaScript only hoists variable declarations, not variable initializations.

  2. To avoid issues because of hoisting, always declare all variables at the beginning of every scope.

  3. Use ES6 - let and const to avoid hoisting.

var x = "Gurukulsight";
function bar() {
 console.log(x); //Error: x is not defined
 let x; //x declaration is not hoisted
}
bar();

3. Destructuring

Destructuring means breaking up the structure. Destructuring is a way to quickly extract the data from a single object or array and assign it to multiple variables within a single statement. ES6 also supports object destructuring.

TypeScript supports the following forms of Destructuring:

  1. Object Destructuring

  2. Array Destructuring

destructuring.ts

let list = ['one', 'two', 'three'];
let [x, y, z] = list; //destructuring the array values into three variables x,y,z

console.log(x); // 'one'
console.log(y); // 'two'
console.log(z); // 'three'

let obj = {x: 'one', y: 'two', z: 'three'};
let {x, y, z} = obj; // destructuring the object properties x, y, z

console.log(x); // 'one'
console.log(y); // 'two'
console.log(z); // 'three'

Destructuring can also be used for passing objects into a function that allows you to extract specific properties from an object.

destructuring_auguments.ts

function greet({firstName, lastName}): void {
 console.log(`Hello, ${firstName} ${lastName}!`);
}

let p1 = { firstName: 'Shailendra', lastName: 'Chauhan' };
let p2 = { firstName: 'Kanishk', lastName: 'Puri' };

greet(p1) // -> Hello, Shailendra Chauhan!
greet(p2) // -> Hello, Kanishk Puri!

Conclusion
Understanding variables in TypeScript is essential for creating effective and maintainable code. You may construct strong programs that are easier to debug and comprehend by properly using let, const, and var, as well as TypeScript's comprehensive type system. Emphasizing recommended practices for variable declaration and name can help you and your team maintain a high level of code quality. Happy coding!

FAQs

let is used to declare block-scoped variables, meaning they are only accessible within the block they are defined in. const is also block-scoped but is used for variables that should not be reassigned after their initial value is set. var, on the other hand, declares function-scoped variables and can lead to unexpected behavior due to hoisting, making it less favorable in modern TypeScript coding. 

 Yes, you can declare a variable without specifying a type, and TypeScript will infer the type based on the initial value. For example, let age = 25; will infer that age is of type number. However, explicitly declaring types is recommended for better clarity and type safety. 

 Use descriptive and meaningful names that reflect the purpose of the variable. It’s a good practice to use camelCase for variable names (e.g., studentCount) and to avoid using single letters or abbreviations unless their meaning is clear in the context. 

Take our Typescript skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article
About Author
Amit Kumar (Software Engineer And Author)

Experienced Software Engineer with a demonstrated history of working in the professional training & coaching industry. Skilled in Asp.net MVC, Angular, Language Integrated Query (LINQ), SQL, C++, and HTML. Strong engineering professional graduated from Sathyabama University.
Accept cookies & close this