Typescript Variable and Operators

Level : Beginner
Mentor: Shailendra Chauhan
Duration : 00:2:15

TypeScript Variables:

TypeScript Variables refer to the named storage locations that can store data during the program's execution. They are a fundamental concept in TypeScript and are used to hold values of various data types.

Example:

// Example of declaring and initializing a TypeScript variable
let message: string = "Hello, TypeScript!";
console.log(message); // Output: Hello, TypeScript!

Variable Declaration:

Variable declaration is the process of introducing a new variable by specifying its name and, optionally, its data type. In TypeScript, you can declare variables using keywords like var, let, and const.

Example:

// Declaration using var
var x: number;
// Declaration using let (preferred in modern TypeScript)
let y: string;
// Declaration using const for constants
const pi: number = 3.14;

Scoping Rules:

Scoping in TypeScript determines the visibility and accessibility of variables within different parts of the code. It helps prevent naming conflicts and manage the lifecycle of variables.

Example:

function exampleScope() {
  if (true) {
    let innerVar = "Inner variable";
  }
  // Cannot access innerVar here - it's out of scope
}

Block Scoping:

Block scoping refers to the scope of a variable being limited to the block (typically enclosed in curly braces) where it is declared. This behavior is seen when using let and const.

Example:

function blockScopeExample() {
  if (true) {
    let blockVar = "Inside block";
    console.log(blockVar); // Output: Inside block
  }
  // Cannot access blockVar here - it's out of scope
} 

Re-declaration and Shadowing:

TypeScript allows you to re-declare a variable using var, but not using let or const. Shadowing occurs when a variable declared within a nested scope has the same name as a variable in the outer scope.

Example:

var x: number = 5;
if (true) {
  var x: number = 10; // Re-declaration of x in the same scope
}
console.log(x); // Output: 10 (the outer x is shadowed)

Hoisting of var:

Variables declared with var are hoisted to the top of their containing function or global scope, allowing you to use them before they are declared.

Example:

console.log(x); // Output: undefined
var x: number = 5;

Hoisting of let:

Variables declared with let are also hoisted but are not initialized. Accessing them before declaration results in a ReferenceError.

Example:

console.log(y); // Error: Cannot access 'y' before initialization
let y: string = "Hello";

const Declarations:

const is used to declare variables that are constant and cannot be reassigned after their initial assignment. They are block-scoped and must be initialized at the time of declaration.

Example:

const pi: number = 3.14;
// pi = 3.14159; // Error: Cannot assign to 'pi' because it is a constant

Arithmetic Operators:

Arithmetic operators in TypeScript are used to perform mathematical calculations such as addition, subtraction, multiplication, division, and more.

Example:

const num1: number = 10;
const num2: number = 5;
const sum: number = num1 + num2;
console.log(`Sum: ${sum}`);

Comparison (Relational) Operators:

Comparison operators in TypeScript are used to compare values and return a boolean result, indicating whether the comparison is true or false.

Example:

const a: number = 10;
const b: number = 5;
const isEqual: boolean = a === b;
console.log(`Is equal: ${isEqual}`);

Logical Operators:

Logical operators in TypeScript are used to perform logical operations like AND, OR, and NOT on boolean values.

Example:

const isSunny: boolean = true;
const isWarm: boolean = false;
const isGoodWeather: boolean = isSunny && isWarm;
console.log(`Is it good weather? ${isGoodWeather}`);

Bitwise Operators:

Bitwise operators in TypeScript perform operations on individual bits of binary numbers.

Example:

const binaryA: number = 0b1010; // 10 in binary
const binaryB: number = 0b1100; // 12 in binary
const result: number = binaryA & binaryB; // Bitwise AND
console.log(`Result: ${result.toString(2)}`); // Convert result to binary string

Assignment Operators:

Assignment operators in TypeScript are used to assign values to variables, often with additional operations like addition or subtraction.

Example:

let x: number = 5;
x += 3; // Equivalent to x = x + 3;
console.log(`Updated x: ${x}`); 

Ternary/Conditional Operator:

The ternary (conditional) operator in TypeScript is a concise way to write conditional expressions that return different values based on a condition.

Example:

const age: number = 20;
const canVote: boolean = age >= 18 ? true : false;
console.log(`Can vote? ${canVote}`);

Concatenation Operator:

TypeScript doesn't have a specific concatenation operator, but you can concatenate strings using the `+` operator.

Example:

const firstName: string = "John";
const lastName: string = "Doe";
const fullName: string = firstName + " " + lastName;
console.log(`Full name: ${fullName}`);

Self-paced Membership
  • 22+ Video Courses
  • 800+ Hands-On Labs
  • 400+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
CONTACT US
Accept cookies & close this