Typescript
1. TypeScript Basics - Types
1.1 Primitive Types:
Understand basic types like string, number, boolean, null, undefined, and symbol.
let name: string = "John";
let age: number = 25;
let isActive: boolean = true;
1.2 Array and Tuples
Array
let numbers: number[] = [1, 2, 3, 4]; // array of numbers let strings: Array<string> = ["apple",
"banana", "cherry"]; // array of strings
let fruits: string[] = ["apple", "banana", "cherry"];
fruits.push("date"); // Adding more items
Tuples – hold different datatypes with fixed number of elements
let person: [string, number] = ["John", 30]; // tuple with string and number let point: [number,
number] = [10, 20]; // tuple with two numbers
Adding More Elements Using push() (Tuple with Rest Element)
let user: [string, number, ...boolean[]] = ["John", 28];
// You can add more elements at the end if you define the tuple to accept additional values (like
`...boolean[]`)
user.push(true); // Adding a boolean value to the tuple
user.push(false);
console.log(user); // Output: ['John', 28, true, false]
Fetching Data from Tuples
let person: [string, number] = ["Alice", 30];
// Accessing elements by index
let name = person[0]; // "Alice"
let age = person[1]; // 30
console.log(`Name: ${name}, Age: ${age}`); // Output: Name: Alice, Age: 30
1.3 Enums
Enums allow for a set of named constants
Examples –
Numeric Enum
enum Direction {
Up, // 0
Down, // 1
Left, // 2
Right // 3
console.log(Direction.Up); // Output: 0
console.log(Direction.Left); // Output: 2
Explicitly Assigning Numeric Values
enum StatusCode {
OK = 200,
NotFound = 404,
InternalServerError = 500
}
String Enums
enum UserRole {
Admin = "ADMIN",
User = "USER",
Guest = "GUEST"
console.log(UserRole.Admin); // Output: ADMIN
console.log(UserRole.Guest); // Output: GUEST
console.log(StatusCode.OK); // Output: 200
console.log(StatusCode.NotFound); // Output: 404
console.log(StatusCode.InternalServerError); // Output: 500
Enum with Computed and Constant Values
enum FileAccess {
Read = 1,
Write,
Execute,
ReadWrite = Read | Write // Computed value using bitwise OR
console.log(FileAccess.Read); // Output: 1
console.log(FileAccess.ReadWrite); // Output: 3 (1 | 2)
1.4 any and unknown
any - allows a value to be of any type
let value: any = 42;
value = "Hello, world!"; // No error
value = true; // No error
value = { name: "John" }; // No error
console.log(value.name); // No error, even though the value is a boolean now
unknown Type
similar to any but, you cannot perform operations on an unknown type unless you first assert or
narrow its type
let value: unknown = 42;
value = "Hello, world!"; // No error
value = true; // No error
// Cannot directly access properties on `unknown` type
// console.log(value. length); // Error: Object is of type 'unknown'
// Narrowing the type first
if (typeof value === "string") {
console.log(value.length); // Now it's safe, as TypeScript knows `value` is a string
1.5 void and never
Void
does not return anything
function logMessage(message: string): void {
console.log(message);
logMessage("Hello, world!"); // Output: Hello, world!
never
A function with a return type of never will either:
• Always throw an error (an exception).
• Never complete (like in an infinite loop).
function throwError(message: string): never {
throw new Error(message);
function infiniteLoop(): never {
while (true) {
// This loop never ends
2. TypeScript Advanced Concepts
2.1 Interface
In TypeScript, an interface is a way to define the structure of an object.
// Define the interface
interface Product {
name: string; // Required property
price: number; // Required property
discount?: number; // Optional property
category: string; // Required property
applyDiscount(): void; // Function type property
// Create an object that follows the Product interface
const laptop: Product = {
name: "Laptop",
price: 1000,
category: "Electronics",
applyDiscount() {
if (this.discount) {
this.price = this.price - this.discount;
console.log(`Discount applied! New price: $${this.price}`);
} else {
console.log("No discount available.");
};
// Create another object with a discount
const phone: Product = {
name: "Phone",
price: 500,
category: "Electronics",
discount: 50, // Optional property
applyDiscount() {
if (this.discount) {
this.price = this.price - this.discount;
console.log(`Discount applied! New price: $${this.price}`);
} else {
console.log("No discount available.");
};
// Test the functionality
laptop.applyDiscount(); // Output: No discount available.
phone.applyDiscount(); // Output: Discount applied! New price: $450
Benefits - Type safety, code readability, maintainability and reusability.
2.2 type alias
a type alias is a way to create a custom name for a type. A type alias is similar to an interface, but it is
more flexible in the types it can represent.
Declaration
// 1. Type Alias for a Primitive Type
type Name = string;
// 2. Type Alias for an Object
type Person = {
name: string;
age: number;
greet(): void;
};
// 3. Type Alias for Union Types
type ID = string | number;
// 4. Type Alias for Function Types
type AddFunction = (a: number, b: number) => number;
// 5. Type Alias for Literal Types (specific set of values)
type Direction = "up" | "down" | "left" | "right";
Using the Type Aliases
// 1. Primitive Type Alias Example
let userName: Name = "Alice"; // Using Name alias for string
console.log(userName); // Output: Alice
// 2. Object Type Alias Example
const john: Person = {
name: "John",
age: 30,
greet() {
console.log("Hello, my name is " + this.name);
};
john.greet(); // Output: Hello, my name is John
// 3. Union Type Alias Example
function printId(id: ID) {
console.log("The ID is: " + id);
printId("abc123"); // Output: The ID is: abc123
printId(101); // Output: The ID is: 101
// 4. Function Type Alias Example
const add: AddFunction = (x, y) => x + y;
console.log(add(2, 3)); // Output: 5
// 5. Literal Type Alias Example
function move(direction: Direction) {
console.log("Moving " + direction);
move("up"); // Output: Moving up
move("down"); // Output: Moving down
// move("forward"); // Error: Argument of type 'forward' is not assignable to parameter of type
'Direction'.
2.3 Function Types
1. Basic Function Type: Defines function signature with parameters and return type.
2. Anonymous Functions: Functions without a name, stored in variables.
3. Arrow Functions: A shorter syntax for functions.
4. Function Type Aliases: Reusable function signatures.
5. Optional Parameters: Parameters that may or may not be provided.
6. Default Parameters: Parameters with default values.
7. Rest Parameters: Accepting multiple arguments of the same type.
8. Void: Functions that don’t return a value.
9. Function Overloading: Multiple function signatures for different use cases.
// 1. Basic Function Type
function add(a: number, b: number): number {
return a + b;
// 2. Anonymous Function (Function Expression)
const subtract = function(a: number, b: number): number {
return a - b;
};
// 3. Arrow Function
const multiply = (a: number, b: number): number => {
return a * b;
};
// 4. Function Type Alias
type Operation = (a: number, b: number) => number;
const divide: Operation = (a, b) => {
return a / b;
};
// 5. Optional Parameters
function greet(name: string, age?: number): string {
return `Hello ${name}${age ? `, you are ${age} years old` : ''}`;
// 6. Default Parameters
function sayHello(name: string = "Stranger"): string {
return `Hello, ${name}!`;
// 7. Rest Parameters
function sum(...numbers: number[]): number {
return numbers.reduce((acc, num) => acc + num, 0);
// 8. Void Return Type
function logMessage(message: string): void {
console.log(message);
// 9. Function Overloading
function greet(person: string): string;
function greet(person: string, age: number): string;
function greet(person: string, age?: number): string {
if (age) {
return `Hello ${person}, you are ${age} years old.`;
} else {
return `Hello ${person}!`;
// Usage examples
console.log(add(5, 3)); // 8
console.log(subtract(10, 4)); // 6
console.log(multiply(4, 2)); // 8
console.log(divide(20, 5)); // 4
console.log(greet("Alice")); // Hello Alice
console.log(greet("Bob", 25)); // Hello Bob, you are 25 years old
console.log(sayHello()); // Hello, Stranger!
console.log(sayHello("John")); // Hello, John!
console.log(sum(1, 2, 3, 4)); // 10
logMessage("This is a test."); // Logs: This is a test.
console.log(greet("Charlie", 30)); // Hello Charlie, you are 30 years old.
2.4 Generics
Generics in TypeScript allow you to create reusable, flexible functions, classes, and interfaces that
can work with different types, without losing type safety.
// 1. Generic Function
function identity<T>(value: T): T {
return value;
let num = identity(10); // num is of type number
let str = identity("Hello"); // str is of type string
// 2. Generic Arrays
function getFirstElement<T>(arr: T[]): T {
return arr[0];
let firstNumber = getFirstElement([1, 2, 3]); // firstNumber is of type number
let firstString = getFirstElement(["a", "b", "c"]); // firstString is of type string
// 3. Generic Class
class Box<T> {
value: T;
constructor(value: T) {
this.value = value;
getValue(): T {
return this.value;
}
}
let numberBox = new Box(123); // Box<number>
let stringBox = new Box("Hello"); // Box<string>
console.log(numberBox.getValue()); // 123
console.log(stringBox.getValue()); // "Hello"
// 4. Generic Interface
interface Pair<T, U> {
first: T;
second: U;
let numberStringPair: Pair<number, string> = { first: 1, second: "Hello" };
let stringBooleanPair: Pair<string, boolean> = { first: "Yes", second: true };
// 5. Generic Function with Constraints
function lengthOf<T extends { length: number }>(item: T): number {
return item.length;
let stringLength = lengthOf("Hello"); // 5
let arrayLength = lengthOf([1, 2, 3]); // 3
// lengthOf(123); // Error: number doesn't have a 'length' property
3. OOPS in typescript
// Abstraction: Abstract class
abstract class Animal {
abstract makeSound(): void; // Abstract method
move() {
console.log('The animal is moving');
// Interface: Defines a structure
interface Employee {
name: string;
position: string;
showDetails(): void;
// Inheritance: Dog class inherits from Animal class
class Dog extends Animal {
name: string;
constructor(name: string) {
super(); // Call parent class constructor
this.name = name;
// Polymorphism: Method Overriding
makeSound() {
console.log(`${this.name} barks.`);
// Class implementing an interface (Employee)
class Manager implements Employee {
name: string;
position: string;
constructor(name: string, position: string) {
this.name = name;
this.position = position;
showDetails() {
console.log(`${this.name} is a ${this.position}`);
// Encapsulation: private properties, getters, and setters
class Car {
private speed: number = 0;
accelerate(amount: number) {
if (amount > 0) {
this.speed += amount;
console.log(`Accelerated to ${this.speed} km/h.`);
getSpeed(): number {
return this.speed;
// Instantiate objects from classes
const dog = new Dog('Buddy');
dog.makeSound(); // Output: Buddy barks.
dog.move(); // Output: The animal is moving
const manager = new Manager('John', 'Manager');
manager.showDetails(); // Output: John is a Manager
const car = new Car();
car.accelerate(50); // Output: Accelerated to 50 km/h
console.log(car.getSpeed()); // Output: 50
// Encapsulation Error: Cannot directly access private property
// console.log(car.speed); // Error: Property 'speed' is private
4. Difference between var, let and const
Var – function scope, can be re-assigned and re-declared
function exampleVar() {
console.log(a); // undefined, because of hoisting
var a = 10;
console.log(a); // 10, after the variable is declared
if (true) {
var a = 20; // Re-declares and modifies the same variable in the function scope
console.log(a); // 20, as 'a' is function-scoped, not block-scoped
exampleVar();
let – block scope(if, for), can be re-assigned but not re-declared
function exampleLet() {
let a = 10;
console.log(a); // 10
if (true) {
let a = 20; // Different 'a' variable in the block scope
console.log(a); // 20
console.log(a); // 10, because the 'a' in the block is different from the one outside
exampleLet();
const – block scope as that of let, can’t re-assign, object mutability(reference won’t be changed but
value gets changed)
function exampleConst() {
const a = 10;
console.log(a); // 10
// a = 20; // Error: Assignment to constant variable
const obj = { name: "John" };
obj.name = "Doe"; // Allowed, because we can modify the object's properties
console.log(obj.name); // "Doe"
// obj = {}; // Error: Assignment to constant variable
exampleConst();
5. Difference between =,==,=== in typescript
= (Assignment Operator):
let a = 5; // Assigns 5 to the variable 'a'
let b = a; // Assigns the value of 'a' to 'b' (so b = 5)
== (Equality Operator - Loose Comparison):
let a = 5;
let b = "5"; // string
console.log(a == b); // true, because '==' coerces the string "5" to a number before comparison
=== (Strict Equality Operator - Strict Comparison):
let a = 5;
let b = "5"; // string
console.log(a === b); // false, because a number is not strictly equal to a string
6. Inbuilt functions in typescript
1. Array Functions
These are methods available on arrays in TypeScript, inherited from JavaScript's Array prototype.
• push(): Adds one or more elements to the end of an array.
let arr = [1, 2, 3];
arr.push(4); // [1, 2, 3, 4]
• pop(): Removes the last element from an array.
let arr = [1, 2, 3];
arr.pop(); // 3
• unshift(): Adds one or more elements to the beginning of an array.
let arr = [1, 2, 3];
arr.unshift(0); // [0, 1, 2, 3]
• shift(): Removes the first element from an array.
let arr = [1, 2, 3];
arr.shift(); // 1
• map():
i/p - function passed on each element of array as expressions
o/p – new array without disturbing existing array
Ex1 -
const numbers: number[] = [1, 2, 3, 4, 5];
// Use map to square each number
const squaredNumbers = numbers.map(num => num * num);
console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]
Ex2-
const numbers: number[] = [10, 20, 30, 40, 50];
// Multiply each element by its index
const indexedNumbers = numbers.map((num, index) => num * index);
console.log(indexedNumbers); // Output: [0, 20, 60, 120, 200]
• filter():
i/p - function passed on each element of array and returns true
o/p – new array without disturbing existing array
Ex- 1
const numbers: number[] = [1, 2, 3, 4, 5, 6];
// Use filter to keep only even numbers
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4, 6]
Ex- 2
const numbers: number[] = [10, 20, 30, 40, 50];
// Keep only elements whose index is even
const evenIndexNumbers = numbers.filter((num, index) => index % 2 === 0);
console.log(evenIndexNumbers); // Output: [10, 30, 50]
• reduce():
Applies a function to an accumulator and each element in the array (from left to right) to reduce it
to a single value.
let arr = [1, 2, 3, 4];
let sum = arr.reduce((acc, val) => acc + val, 0); // 10
concat(): Merges two or more arrays
let arr1 = [1, 2];
let arr2 = [3, 4];
let merged = arr1.concat(arr2);
console.log(merged); // Output: [1, 2, 3, 4]
Sorting and Reversing
sort(): Sorts an array (by default, sorts as strings)
let arr = [30, 5, 20, 15];
arr.sort((a, b) => a - b); // Ascending order
console.log(arr); // Output: [5, 15, 20, 30]
reverse(): Reverses an array
let arr = [1, 2, 3, 4];
arr.reverse();
console.log(arr); // Output: [4, 3, 2, 1]
Converting and Joining
join(): Converts an array to a string
let arr = ["Apple", "Banana", "Mango"];
console.log(arr.join(", ")); // Output: "Apple, Banana, Mango"
toString(): Converts an array to a string
let arr = [1, 2, 3];
console.log(arr.toString()); // Output: "1,2,3"
splice - Removes or replaces elements
array.splice(startIndex, deleteCount, item1?, item2?, ...);
1. Removing Elements
If you specify only startIndex and deleteCount, it removes elements from the array.
let arr = [10, 20, 30, 40, 50];
let removed = arr.splice(1, 2); // Removes 20 and 30
console.log(arr); // Output: [10, 40, 50]
console.log(removed); // Output: [20, 30]
2. Inserting Elements
You can insert elements by providing item1, item2, ... after deleteCount.
let arr = [10, 20, 30];
arr.splice(1, 0, 15, 18); // Inserts 15, 18 at index 1
console.log(arr); // Output: [10, 15, 18, 20, 30]
3. Replacing Elements
You can replace elements by providing new values for the removed elements.
let arr = [10, 20, 30, 40];
arr.splice(1, 2, 25, 35); // Removes 20, 30 and adds 25, 35
console.log(arr); // Output: [10, 25, 35, 40]
4. Removing All Elements from an Index
If you provide a large deleteCount, it removes all elements from startIndex to the end.
let arr = [1, 2, 3, 4, 5];
arr.splice(2); // Removes all elements from index 2
console.log(arr); // Output: [1, 2]
5. Removing Only One Element
If deleteCount is 1, it removes a single element.
let arr = [100, 200, 300, 400];
arr.splice(2, 1); // Removes 300
console.log(arr); // Output: [100, 200, 400]
slice - Extracts a portion of an array
Syntax
array.slice(startIndex, endIndex);
startIndex: The index where extraction starts (inclusive).
endIndex (optional): The index where extraction ends (exclusive). If omitted, it extracts till
the end.
1. Extracting a Subarray
let arr = [10, 20, 30, 40, 50];
let newArr = arr.slice(1, 4); // Extracts elements from index 1 to 3
console.log(newArr); // Output: [20, 30, 40]
console.log(arr); // Original array remains unchanged: [10, 20, 30, 40, 50]
2. Extracting Till the End
If endIndex is omitted, it extracts all elements from startIndex to the end.
let arr = [1, 2, 3, 4, 5];
let newArr = arr.slice(2); // Extracts from index 2 to the end
console.log(newArr); // Output: [3, 4, 5]
3. Using Negative Indices
Negative indices count from the end of the array.
-1 refers to the last element, -2 refers to the second-last, etc.
let arr = [10, 20, 30, 40, 50];
console.log(arr.slice(-3)); // Output: [30, 40, 50] (Last 3 elements)
console.log(arr.slice(-4, -1)); // Output: [20, 30, 40] (Excludes last element)
4. Copying an Entire Array
You can create a shallow copy of an array using slice().
let arr = [1, 2, 3, 4];
let copyArr = arr.slice(); // Copies the entire array
console.log(copyArr); // Output: [1, 2, 3, 4]
console.log(copyArr === arr); // Output: false (Different references)
2. String Functions
TypeScript also supports many inbuilt string methods from JavaScript.
• toUpperCase():
Converts a string to uppercase.
let str = "hello";
let upper = str.toUpperCase(); // "HELLO"
• toLowerCase():
Converts a string to lowercase.
let str = "HELLO";
let lower = str.toLowerCase(); // "hello"
• trim():
Removes whitespace from both ends of a string.
let str = " hello ";
let trimmed = str.trim(); // "hello"
• substring():
Extracts a part of a string between two indices.
let str = "hello";
let sub = str.substring(1, 4); // "ell"
• replace():
Replaces a substring with a new substring.
let str = "hello world";
let newStr = str.replace("world", "TypeScript"); // "hello TypeScript"
• split():
Splits a string into an array of substrings.
let str = "apple,banana,cherry";
let arr = str.split(","); // ["apple", "banana", "cherry"]
3. Number Functions
TypeScript supports all the number functions from JavaScript, including:
• toFixed():
Formats a number to a fixed number of decimal places.
let num = 3.14159;
let fixed = num.toFixed(2); // "3.14"
• parseInt():
Converts a string to an integer.
let str = "42";
let num = parseInt(str, 10); // 42
• parseFloat():
Converts a string to a floating-point number.
let str = "3.14";
let num = parseFloat(str); // 3.14
• isNaN():
Determines whether a value is NaN (Not-a-Number).
let val = NaN;
let result = isNaN(val); // true
4. Object Functions
Objects in TypeScript have the same built-in methods from JavaScript.
• Object.keys():
Returns an array of a given object's own enumerable property names.
let obj = { a: 1, b: 2 };
let keys = Object.keys(obj); // ["a", "b"]
• Object.values():
Returns an array of a given object's own enumerable property values.
let obj = { a: 1, b: 2 };
let values = Object.values(obj); // [1, 2]
• Object.entries():
Returns an array of a given object's own enumerable string-keyed property [key, value] pairs.
let obj = { a: 1, b: 2 };
let entries = Object.entries(obj); // [["a", 1], ["b", 2]]
7. Operators in typescript
// 1. Arithmetic Operators
let a = 10;
let b = 5;
console.log(a + b); // 15 (Addition)
console.log(a - b); // 5 (Subtraction)
console.log(a * b); // 50 (Multiplication)
console.log(a / b); // 2 (Division)
console.log(a % b); // 0 (Modulus)
a++; // Increment
console.log(a); // 11
b--; // Decrement
console.log(b); // 4
// 2. Assignment Operators
a = 10;
a += 5; // a = a + 5
console.log(a); // 15
a -= 3; // a = a - 3
console.log(a); // 12
a *= 2; // a = a * 2
console.log(a); // 24
// 3. Comparison Operators
console.log(a == b); // false (values are not equal)
console.log(a === b); // false (values and types are not equal)
console.log(a != b); // true (values are not equal)
console.log(a > b); // false (a is not greater than b)
console.log(a < b); // true (a is less than b)
// 4. Logical Operators
let x = true;
let y = false;
console.log(x && y); // false (AND)
console.log(x || y); // true (OR)
console.log(!x); // false (NOT)
// 5. Ternary Operator
let result = a > b ? "a is greater" : "b is greater";
console.log(result); // "b is greater"
// 6. Type Operators
let c = "Hello";
let d = 10;
console.log(typeof c); // "string"
console.log(typeof d); // "number"
7. Spread and Rest Operators
Ex -1
let arr1 = [1, 2, 3];
let arr2 = [...arr1]; // Spread elements of arr1 into arr2
console.log(arr2); // [1, 2, 3]
Ex-2
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let combined = [...arr1, ...arr2]; // Spread arr1 and arr2 into a new array
Ex-3
let arr = [2, 3, 4];
let newArr = [1, ...arr, 5]; // Add elements at the beginning and end
console.log(newArr); // [1, 2, 3, 4, 5]
console.log(combined); // [1, 2, 3, 4, 5, 6]
Ex-4
let person = { name: "John", age: 30 };
let newPerson = { ...person }; // Copy all properties of person to newPerson
console.log(newPerson); // { name: "John", age: 30 }
Ex-5 - object
let person = { name: "John", age: 30 };
let contact = { phone: "123-456", email: "john@example.com" };
let mergedPerson = { ...person, ...contact }; // Merge person and contact
console.log(mergedPerson);
// { name: "John", age: 30, phone: "123-456", email: "john@example.com" }
Ex-6 - function
function sum(a: number, b: number, c: number): number {
return a + b + c;
let numbers = [1, 2, 3];
console.log(sum(...numbers)); // 6
8. Nullish Coalescing Operator
Ex 1 - with null
let name: string | null = null;
let defaultName = "Guest";
let result = name ?? defaultName;
console.log(result); // "Guest"
Ex 2 – with undefined
let age: number | undefined = undefined;
let defaultAge = 25;
let result = age ?? defaultAge;
console.log(result); // 25
9. Optional Chaining Operator
let user = { address: { city: "New York" } };
console.log(user.address?.city); // "New York"
console.log(user.contact?.phone); // undefined (no error)
8. Functions
const numbers = [1, 2, 3, 4, 5, 6];
// 1. filter: Filters elements based on a condition
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log("filter:", evenNumbers); // Output: [2, 4, 6]
// 2. map: Transforms each element
const doubledNumbers = numbers.map(num => num * 2);
console.log("map:", doubledNumbers); // Output: [2, 4, 6, 8, 10]
// 3. reduce: Reduces array to a single value
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log("reduce:", sum); // Output: 21
// 4. find: Finds the first matching element
const firstGreaterThanThree = numbers.find(num => num > 3);
console.log("find:", firstGreaterThanThree); // Output: 4
// 5. findIndex: Finds the index of the first matching element
const index = numbers.findIndex(num => num > 3);
console.log("findIndex:", index); // Output: 3
// 6. every: Checks if all elements satisfy a condition
const allEven = numbers.every(num => num % 2 === 0);
console.log("every:", allEven); // Output: false
// 7. some: Checks if at least one element satisfies a condition
const hasGreaterThanFour = numbers.some(num => num > 4);
console.log("some:", hasGreaterThanFour); // Output: true
// 8. forEach: Executes a function for each element
console.log("forEach:");
numbers.forEach(num => console.log(num)); // Output: 1 2 3 4 5 6 (printed separately)
// 9. sort: Sorts the array in ascending order
const unsortedNumbers = [5, 3, 8, 1, 2];
const sortedNumbers = unsortedNumbers.sort((a, b) => a - b);
console.log("sort:", sortedNumbers); // Output: [1, 2, 3, 5, 8]
9. Decision and loopin statements
// 1. Decision-Making Statements
// if-else
const num = 10;
if (num > 0) {
console.log("Positive number");
} else {
console.log("Negative number");
// if-else if
const marks = 85;
if (marks >= 90) {
console.log("Grade: A+");
} else if (marks >= 75) {
console.log("Grade: A");
} else {
console.log("Grade: B");
// switch
const day = 2;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
default:
console.log("Invalid day");
// 2. Looping Statements
// for loop
for (let i = 1; i <= 5; i++) {
console.log(`for loop: ${i}`); // Output: 1 2 3 4 5
// for...of loop
const fruits = ["Apple", "Banana", "Cherry"];
for (const fruit of fruits) {
console.log(`for...of loop: ${fruit}`); // Output: Apple Banana Cherry
// for...in loop
const person = { name: "John", age: 30 };
for (const key in person) {
console.log(`for...in loop: ${key} = ${person[key]}`); // Output: name = John, age = 30
// while loop
let i = 1;
while (i <= 5) {
console.log(`while loop: ${i}`); // Output: 1 2 3 4 5
i++;
// do-while loop
let j = 1;
do {
console.log(`do-while loop: ${j}`); // Output: 1 2 3 4 5
j++;
} while (j <= 5);
// Break and Continue Statements
// break
for (let k = 1; k <= 5; k++) {
if (k === 3) break; // Stops the loop when k === 3
console.log(`break example: ${k}`); // Output: 1 2
// continue
for (let k = 1; k <= 5; k++) {
if (k === 3) continue; // Skips the iteration when k === 3
console.log(`continue example: ${k}`); // Output: 1 2 4 5
10. Array and Map(similar to that of list, dictionary in
C#)
Consider normal array of elements
// Declare and Initialize an Array
const numbers: number[] = [10, 20, 30, 40];
// Add a new element
numbers.push(50); // Add at the end
numbers.unshift(5); // Add at the beginning
console.log("Array after adding elements:", numbers); // [5, 10, 20, 30, 40, 50]
// Fetch all elements
console.log("Fetching all elements from the array:");
numbers.forEach((num) => console.log(num));
// Check if a particular element exists and remove it
const itemToRemove = 30;
if (numbers.includes(itemToRemove)) {
const index = numbers.indexOf(itemToRemove);
numbers.splice(index, 1); // Remove the item
console.log(`${itemToRemove} removed. Updated Array:`, numbers); // [5, 10, 20, 40, 50]
} else {
console.log(`${itemToRemove} not found in the array.`);
// Declare and Initialize a Map
const map = new Map<number, string>([
[1, "One"],
[2, "Two"],
[3, "Three"],
]);
// Add new elements to the Map
map.set(4, "Four"); // Add a new key-value pair
map.set(5, "Five");
console.log("Map after adding elements:");
map.forEach((value, key) => console.log(`Key: ${key}, Value: ${value}`));
// Fetch all elements
console.log("Fetching all key-value pairs from the map:");
map.forEach((value, key) => console.log(`Key: ${key}, Value: ${value}`));
// Check if a key exists and remove it
const keyToRemove = 3;
if (map.has(keyToRemove)) {
map.delete(keyToRemove); // Remove the key-value pair
console.log(`Key ${keyToRemove} removed. Updated Map:`);
map.forEach((value, key) => console.log(`Key: ${key}, Value: ${value}`));
} else {
console.log(`Key ${keyToRemove} not found in the Map.`);
Consider of array of objects
// Declare and Initialize an Array of Objects
interface Person {
id: number;
name: string;
const people: Person[] = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
{ id: 3, name: "Charlie" },
];
// Add a new object to the Array
const newPerson: Person = { id: 4, name: "David" };
people.push(newPerson);
console.log("Array after adding a new person:", people);
// Fetch all objects (People)
console.log("Fetching all people:");
people.forEach((person) => console.log(`ID: ${person.id}, Name: ${person.name}`));
// Check if a person with a specific ID exists and remove it
const idToRemove = 2;
const indexToRemove = people.findIndex((person) => person.id === idToRemove);
if (indexToRemove !== -1) {
const removedPerson = people.splices(indexToRemove, 1);
console.log(`Person with ID ${idToRemove} removed. Removed:`, removedPerson);
} else {
console.log(`Person with ID ${idToRemove} not found.`);
// Declare and Initialize a Map of Objects
const peopleMap = new Map<number, Person>([
[1, { id: 1, name: "Alice" }],
[2, { id: 2, name: "Bob" }],
[3, { id: 3, name: "Charlie" }],
]);
// Add a new object to the Map
const newPersonMap: Person = { id: 4, name: "David" };
peopleMap.set(newPersonMap.id, newPersonMap);
console.log("Map after adding a new person:");
peopleMap.forEach((person, key) => console.log(`ID: ${key}, Name: ${person.name}`));
// Fetch all objects (People) from the Map
console.log("Fetching all people from the map:");
peopleMap.forEach((person, key) => console.log(`ID: ${key}, Name: ${person.name}`));
// Check if a person with a specific ID exists and remove it
const idToRemoveMap = 2;
if (peopleMap.has(idToRemoveMap)) {
const removedPersonMap = peopleMap.get(idToRemoveMap);
peopleMap.delete(idToRemoveMap);
console.log(`Person with ID ${idToRemoveMap} removed. Removed:`, removedPersonMap);
} else {
console.log(`Person with ID ${idToRemoveMap} not found.`);