Introduction to TypeScript

TypeScript is an improved version of JavaScript. It includes everything that JavaScript has, plus extra features like data types, interfaces, and enums.

These features help developers find mistakes while writing code instead of after running it.

TypeScript makes code easier to read, understand, and maintain, especially in large projects.

Before running, TypeScript code is converted into JavaScript because browsers and Node.js can only run JavaScript.


Installing TypeScript

Before TypeScript, you need to install Node.js on your system.

Step 1: Install Node.js

  1. Visit the official Node.js website:
  2. Download the LTS (Long-Term Support) version.
  3. Run the installer and complete the installation.
Verify the Installation

Open Command Prompt or Terminal and run:

node -v

Check the npm version:

npm -v

Step 2: Install TypeScript

Install TypeScript globally using npm:

npm install -g typescript

What does this command mean?

  • npm → Node Package Manager
  • install → Installs a package
  • -g → Installs the package globally, so it can be used from any folder
  • typescript → The TypeScript package

Step 3: Verify TypeScript Installation

tsc -v

Write Your First TypeScript Program

Create a file named: hello.ts

console.log("Hi Kapoor");

let message: string = "Hello Kapoor";
console.log(message);

Variables in Typescripts

Variables in TypeScript are used to store data. In other words, variables are containers that hold data values.

Types of Variable Declarations

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

// Explicit typing
const username: string = "Kapoor";
let count: number = 10;
let isCompleted: boolean = false;

// Type Inference (TypeScript automatically detects 'string')
let city = "Noida";

const: Block-scoped constant (cannot be reassigned). Use by default.

let: Block-scoped variable (can be reassigned).

var: Function-scoped variable (avoid in modern TypeScript).

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.

Note: Rules for Variable Names

  • Can contain letters, digits, `_`, and `$`.
  • Cannot begin with a digit.
  • Are case-sensitive.
  • Cannot use reserved keywords.

Data Types in TypeScript

Data types define the kind of values a variable can store. TypeScript uses static typing to improve code safety and readability.

1. Primitive Types

The foundational types inherited directly from JavaScript:

  • string: Textual data ("Hello", 'Playwright', `automation`).
  • number: Numeric values, including integers, floating points, hex, and binary (42, 3.14, 0xFF).
  • boolean: Logical true/false (true, false).
  • null: Intentional absence of any object value.
  • undefined: Variables that have been declared but not initialized.
  • symbol: Unique and immutable primitive values used as object keys.
  • bigint: Large integers that exceed standard number precision (9007199254740991n).
const testName: string = "Logic Nextgen Kapoor";
let timeout: number = 5000;
let isPassed: boolean = true;

2. Object Data Types

Object types are more complex structures that can hold multiple values. Some common object types include:

Used to structure grouped data and collections:

  • Arrays: Homogeneous lists of elements (number[] or Array<string>).
  • Tuples: Fixed-length arrays where each element position has a specific type ([string, number]).
  • Objects: Structured key-value pairs ({ id: number; name: string }).
const tags: string[] = ["smoke", "regression"];
const responseStatus: [number, string] = [200, "OK"]; // Tuple

1 Object

The object type represents a non-primitive type that can hold various properties.

let person: object = {
    name: "kapoor",
    age: 25
};

2 Array

An Array in typescript can hold a collection of values of a specific type. You can define an array using the syntax type[] or Array<type>.

let numbers: number[] = [1, 2, 3, 4];
let strings: Array = ["apple", "banana", "cherry"];

3 Tuple

A Tuple represents an array with a fixed number of elements, each of which can have a different type.

let tuple: [string, number] = ["Keshav", 30];

3. Special Types

TypeScript provides special types to handle specific scenarios:

  • any: Opts out of type checking completely. Use sparingly.
  • unknown: Type-safe counterpart to any. Must perform type checks before operating on the variable.
  • void: Represents the absence of a return value (commonly used in functions).
  • never: Represents values that never occur (e.g., functions that throw errors or never finish executing).

1 Any Type

The any type allows any value, effectively disabling type checking for that variable.

let variable: any = "Hello";
variable = 5; // Still valid

2 Unknown

The unknown type is safer than any. You cannot perform operations on an unknown type until you perform type checking.

let value: unknown = 5;
// console.log(value.toFixed(2)); // Error: Object is of type 'unknown'

3 Void

The void type is used for functions that do not return a value.

function logMessage(message: string): void {
    console.log(message);
}

4 Never

The never type represents a type that never occurs, such as a function that always throws an error.

function throwError(message: string): never {
    throw new Error(message);
}

Conditional statements – Simple if, if-else, Ladder if else, Nested if else

Conditional statements allow your program to make decisions and execute specific blocks of code based on whether a condition evaluates to true or false.

1. Simple if

Executes a block of code only if the specified condition is true. If the condition is false, the code block is skipped entirely.

TypeScript

const isElementVisible: boolean = true;

if (isElementVisible) {
  console.log("Clicking the element.");
}

2. if else

Provides an alternative execution path. Executes the if block when the condition is true, and the else block when it is false.

TypeScript

const statusCode: number = 200;

if (statusCode === 200) {
  console.log("Request successful.");
} else {
  console.log("Request failed.");
}

3. Ladder if else (Else-If Ladder)

Tests multiple conditions sequentially. It executes the block belonging to the first condition that evaluates to true. If none match, the final else block runs.

TypeScript

const score: number = 85;

if (score >= 90) {
  console.log("Grade: A");
} else if (score >= 80) {
  console.log("Grade: B");
} else if (score >= 70) {
  console.log("Grade: C");
} else {
  console.log("Grade: F");
}

4. Nested if else Statement

An if or if...else statement placed inside another if or else block. Useful for checking secondary conditions after a primary condition passes.

TypeScript

const isLoggedIn: boolean = true;
const userRole: string = "admin";

if (isLoggedIn) {
  console.log("User Mr. kapoor authenticated.");
  
  // Nested check
  if (userRole === "admin") {
    console.log("Access granted to Admin Dashboard.");
  } else {
    console.log("Access granted to Standard User Dashboard.");
  }
} else {
  console.log("Access denied. Please log in first.");
}

Loop

Loops in TypeScript execute a block of code repeatedly as long as a specified condition remains true. TypeScript supports all standard JavaScript loops and adds type safety when iterating over arrays, objects, and collections.

1. Traditional or Simple for Loop

Best when you know the exact number of iterations in advance.

TypeScript

for (let i = 0; i < 5; i++) {
    console.log(i);
}

2. for of Loop (Iterating Values)

Iterates directly over the values of an iterable object like an Array, String, Map, or Set.

TypeScript

const browsers: string[] = ["chromium", "firefox", "webkit"];

for (const browser of browsers) {
  console.log(`Testing on: ${browser}`);
}

3. for in Loop (Iterating Keys)

Iterates over the enumerable keys/properties of an object or indices of an array.

TypeScript

const userRole = { admin: true, editor: false, viewer: false };

for (const role in userRole) {
  console.log(`Role: ${role}`); // Outputs: admin, editor, viewer
}

4. while Loop

Executes as long as the condition is true. The condition is checked before entering the loop body.

TypeScript

let i = 0;

while (i < 5) {
    console.log(i);
    i++;
}

5. do-while Loop

Executes the code block at least once before checking the condition.

TypeScript

let i = 0;

do {
    console.log(i);
    i++;
} while (i < 5);

6. forEach

In TypeScript, forEach() is an array method, not a traditional loop statement. It calls a callback function once for each element in an array.

let fruits: string[] = ["Apple", "Banana", "Mango", "Orange"];

fruits.forEach((fruit) => {
    console.log(fruit);
});

Break and continue

break and continue are used to control the execution of loops.

1. break statement

break stops the entire loop immediately.

for (let i = 1; i <= 5; i++) {
    if (i = = = 3) {
        break;
    }
    console.log(i);
}

2. continue statement

continue skips the current iteration and moves to the next one.

for (let i = 1; i <= 5; i++) {
    if (i = = = 3) {
        continue;
    }
    console.log(i);
}


Array

An array in TypeScript is used to store multiple values in a single variable.

For example, instead of creating separate variables for three fruits, we can store all three fruits in one array.

let fruits: string[] = ["Apple", "Banana", "Mango"];

console.log(fruits);

let fruits: string[] = ["Apple", "Banana", "Mango"];

console.log(fruits[0]); // Apple
console.log(fruits[1]); // Banana
console.log(fruits[2]); // Mango

let numbers: number[] = [10, 20, 30];

for (let i = 0; i < numbers.length; i++) {
    console.log(numbers[i]);
}

let numbers: number[] = [10, 20, 30, 40];

console.log(numbers[2]);
console.log(numbers.length);

let names: string[] = ["Keshav", "Kapoor", "Komal"];
console.log(names);


Switch Case

The switch statement is used when you want to execute different blocks of code based on a value.

let day: number = 2;

switch (day) {
    case 1:
        console.log("Monday");
        break;

    case 2:
        console.log("Tuesday");
        break;

    case 3:
        console.log("Wednesday");
        break;

    default:
        console.log("Invalid day");
}


Class and Object in TypeScript

In TypeScript, a class is a blueprint, and an object is an instance created from that class.

Think of a house:

  • Class: The blueprint (map) of a house.
  • Object: The actual house built using that blueprint.

   class Person {
   
        test1() {
            console.log("I am Test1 Function");
            
        }

        test2() {
            console.log("I am Test2 Function");
        }

    }



    let obj = new Person();
    obj.test1();
    obj.test2();


Functions in TypeScript

A function is a block of code designed to perform a specific task. You can call it whenever you need to execute that code.

1. Simple function example

function greet() {
    console.log("Hello World");
}

greet();
Explanation:
- function — keyword used to declare a function.
- greet — function name.
- { } — contains the code to execute.
- greet() — calls the function.
class Student {
    display(): void {
        console.log("Student details");
    }
}

let s1 = new Student();
s1.display();


2. Function with parameters

Parameters allow you to pass values into a function.

function add(a: number, b: number) {
    console.log(a + b);
}

add(10, 20);
add(30, 40);

3. Function with a return value

The return statement sends a result back to the caller.

function multiply(a: number, b: number): number {
    return a * b;
}

let result = multiply(5, 4);

console.log(result);

4. Function with an if-else condition

function checkAge(age: number): void {
    if (age >= 18) {
        console.log("You are eligible to vote");
    } else {
        console.log("You are not eligible to vote");
    }
}

checkAge(25);
checkAge(15);

Arrow function in TypeScript

Arrow functions provide a shorter syntax.

const subtract = (a: number, b: number): number => {
    return a - b;
};

console.log(subtract(20, 10));




Local vs Static vs Class Variable in TypeScript

In TypeScript, variables can have different scopes and lifetimes. Let’s understand them with simple examples.

1. Local Variable

A local variable is declared inside a method or function. It can only be accessed within that function or method.

class Student {
    display(): void {
        let name: string = "Rahul";
        console.log(name);
    }
}

let s1 = new Student();
s1.display();
Here, name is a local variable because it is declared inside display().

2. Class Variable (Instance Variable)

A class or instance variable is declared inside a class but outside its methods. Each object gets its own instance variable.

class Student {
    name: string;

    constructor(name: string) {
        this.name = name;
    }

    display(): void {
        console.log(this.name);
    }
}

let s1 = new Student("Rahul");
let s2 = new Student("Amit");

s1.display();
s2.display();
Here, name is an instance property. s1 and s2 have their own separate values.

3. Static Variable

A static variable belongs to the class itself, not to individual objects. In TypeScript, use the static keyword.

class Student {
    static school: string = "ABC School";

    display(): void {
        console.log(Student.school);
    }
}

let s1 = new Student();
s1.display();

console.log(Student.school);
Notice that we access school using Student.school, not s1.school.

All three Variable together in example – Local vs Static vs Class Variable

class Employee {
    company: string = "IBM";            // Instance variable
    static country: string = "India";   // Static variable

    display(): void {
        let salary: number = 50000;     // Local variable

        console.log(this.company);
        console.log(Employee.country);
        console.log(salary);
    }
}

let e1 = new Employee();
e1.display();
Remember:
- Local → belongs to a function's scope.
- Instance → belongs to an individual object.
- Static → belongs to the class itself.

Optional Parameters in TypeScript

An optional parameter is a parameter that you don’t have to pass when calling a function.

In TypeScript, we use the ? symbol to make a parameter optional.

class Test1 
    {

        printAge(name:string, age?: number) {

            if (age ! = = undefined) {
                console.log(age);
            }
            else {
                console.log("Age not provided");
            }
        }

    }

    let obj = new Test1();
    obj.printAge("Keshav");
    obj.printAge("Keshav",20);

Inheritance in TypeScript

nheritance is an OOP concept in which one class can acquire the properties and methods of another class.

In simple words, a child class can reuse the code of a parent class.

For example, a Dog is an Animal. The Dog class can inherit common behavior such as eating from the Animal class.

class Animal {
    eat(): void {
        console.log("Animal is eating");
    }
}

class Dog extends Animal {
    bark(): void {
        console.log("Dog is barking");
    }
}

let d1 = new Dog();

d1.eat();
d1.bark();

Method Overloading in TypeScript

Method overloading means defining multiple method signatures with the same name but different parameter types or numbers of parameters.

In TypeScript, you write multiple overload signatures and provide one implementation that handles those variations.

class Hello1 {

    // Overload signatures
    add(a: number, b: number): number;
    add(a: string, b: string): string;

    // Single implementation
    add(a: any, b: any): any {
        return a + b;
    }
}

let obj = new Hello1();

console.log(obj.add(2, 3));
console.log(obj.add("Hello ", "India"));

Constructor in TypeScript

A constructor is a special method in a class that is automatically called when you create an object using the new keyword.

It is mainly used to initialize object properties.

class Student {

    name: string;

    constructor() {
        this.name = "Keshav";
    }

    display(): void {
        console.log(this.name);
    }
}

let s1 = new Student();

s1.display();

Constructor with parameters

You can pass values to a constructor when creating an object.

class Student {

    name: string;
    age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }

    display(): void {
        console.log(this.name + " " + this.age);
    }
}

let s1 = new Student("Keshav", 25);
let s2 = new Student("Krishna", 28);

s1.display();
s2.display();

Important constructor rules
Rule	Explanation
Name=	Must be constructor
Return type=	 Cannot declare a return type such as void
Automatic call=	 Runs when an object is created with new
Parameters=	 Can accept values
Number per class= 	A class can have only one constructor implementation

Method Overriding in TypeScript

Method overriding means a child class provides its own implementation of a method that is already defined in its parent class.

In simple words, the parent has a method, but the child changes how that method behaves.

class Animal {

    sound(): void {
        console.log("Animal makes a sound");
    }
}

class Dog extends Animal {

    sound(): void {
        console.log("Dog barks");
    }
}

let obj = new Dog();

obj.sound();

Explanation

  • Animal is the parent class.
  • Dog is the child class.
  • extends establishes inheritance.
  • Both classes have a method named sound().
  • The child class overrides the parent’s implementation.
  • obj.sound() executes the Dog implementation.

Access Modifiers in TypeScript

Access modifiers define where class properties and methods can be accessed.

TypeScript has three main access modifiers:

  1. public
  2. private
  3. protected

1. Public

A public property or method can be accessed from anywhere. It is the default access level in TypeScript

2. Private

A private property or method can only be accessed within the class where it is declared.

3. Protected

A protected property or method can be accessed inside its class and its subclasses, but not directly through an object.


Interface in TypeScript

An interface in TypeScript defines the structure that an object or class should follow. It specifies which properties and methods are required, along with their types.

Think of an interface as a set of rules that your code must follow.

1. Simple interface example
interface Student {
    name: string;
    age: number;
}

let s1: Student = {
    name: "Rahul",
    age: 25
};

console.log(s1.name);
console.log(s1.age);

Multiple Inheritance in TypeScript

Multiple inheritance means a class inherits properties and methods from more than one parent class.

Important: TypeScript does not support multiple inheritance through classes directly. However, you can achieve similar functionality using multiple interfaces.

1. Multiple inheritance using interfaces

Suppose a person can both drive and swim. We can define two interfaces and implement both in one class.

interface Driving {
    drive(): void;
}

interface Swimming {
    swim(): void;
}

class Person implements Driving, Swimming {

    drive(): void {
        console.log("Person can drive");
    }

    swim(): void {
        console.log("Person can swim");
    }
}

let p1 = new Person();

p1.drive();
p1.swim();

Abstract Class in TypeScript

An abstract class is a class that cannot be instantiated directly. It is designed to act as a base class for other classes.

In simple words, an abstract class provides a common structure that child classes can inherit and implement.

abstract class Animal {

    abstract sound(): void;

    eat(): void {
        console.log("Animal is eating");
    }
}

class Dog extends Animal {

    sound(): void {
        console.log("Dog barks");
    }
}

let d1 = new Dog();

d1.sound();
d1.eat();

Explanation

  • abstract class Animal : defines an abstract class.
  • abstract sound(): void declares a method without an implementation.
  • eat() is a normal method with an implementation.
  • Dog extends Animal inherits from the abstract class.
  • Dog must implement the abstract sound() method.
  • new Animal() is not allowed because Animal is abstract.

Abstract class vs. interface

Abstract classInterface
Uses abstract classUses interface
Can contain implemented methodsDefines a type contract, not method implementations
Can have a constructor and instance propertiesCannot have a constructor or instance fields
A class can extend only one classA class can implement multiple interfaces
Cannot be instantiated directlyCannot be instantiated directly

Type Conversion in TypeScript

Type conversion means converting a value from one data type to another, such as a string to a number or a number to a string.

let num: number = 100;

let value: string = String(num);

console.log(value);
console.log(typeof value);


Type Coercion in TypeScript

Type coercion means JavaScript automatically converts a value from one data type to another during an operation. TypeScript follows JavaScript’s runtime behavior.

In simple words:

  • Type conversion: You convert the type manually.
  • Type coercion: JavaScript converts the type automatically.
let a: any = "10";
let b: any = 20;

console.log(a + b);

Rest Parameter in TypeScript

A Rest Parameter allows a function to accept any number of arguments and collect them into a single array.

In TypeScript, we use three dots (...) before the parameter name.

function add(...numbers: number[]): void {
    console.log(numbers);
}

add(10, 20, 30);
add(1, 2, 3, 4, 5);

Explanation:

  • ...numbers collects all arguments into an array.
  • number[] means the array contains numbers.
  • You can pass any number of numeric arguments.

String methods

1. slice() — Extract part of a string
let text: string = "India";
console.log(text.slice(0, 2));


Output:
In

- 0 is the starting index.
- 2 is the ending index, which is excluded.


******************************************************************************

2. substring() — Extract part of a string
let text1: string = "Hello World";
console.log(text1.substring(6, 11));



Output:
World


It extracts characters from index 6 up to, but not including, index 11.


******************************************************************************

3. replace() — Replace part of a string
let text2: string = "Hello Keshav";
let result = text2.replace("Keshav", "Amit");
console.log(result);


Output:
Hello Amit


It replaces the first matching occurrence of "Keshav" with "Amit".


******************************************************************************


4. split() — Convert a string into an array
let text3: string = "Java,Python,TypeScript";
let result3 = text3.split(",");
console.log(result3);


Output:
[ 'Java', 'Python', 'TypeScript' ]

The comma is used as the separator.

******************************************************************************

5. includes() — Check whether a string contains a value
let text4: string = "I am learning TypeScript";
console.log(text4.includes("TypeScript"));


Output:
true


It returns a Boolean value: true if the substring is found and false otherwise.

Date object and its methods

let today: Date = new Date();

console.log(today);
console.log(today.getFullYear());
console.log(today.getMonth());

Explanation:

  • new Date() creates a date object representing the current date and time.
  • getFullYear() returns the year, such as 2026.
  • getMonth() returns the month from 0 to 11, not 1 to 12.

For example, October returns 9 because January is 0.

To get the month from 1 to 12, use:

console.log(today.getMonth() + 1);
//Format a date
let date: Date = new Date();

console.log(date.toLocaleDateString());

Try-Catch in TypeScript

In TypeScript, try-catch is used to handle errors without abruptly stopping the normal flow of your program.

  • try — contains code that might cause an error.
  • catch — handles the error if one occurs.
  • finally — optional block that executes whether an error occurs or not.
try {
    console.log("Program started");

    let result = 10 / 0;
    console.log(result);

} catch (error) {
    console.log("An error occurred");

} finally {
    console.log("Program completed");
}

Demonstration of custom error message

function checkAge(age: number) {
    if (age < 18) {
        throw new Error("Age must be 18 or above");
    }

    console.log("You are eligible");
}

try {
    checkAge(15);
} catch (error) {
    console.log(error);
}

Promise and Callback in TypeScript

In TypeScript, callbacks and promises are used to handle asynchronous operations, such as fetching data from an API or waiting for a task to finish.

1. Callback example

A callback is a function passed as an argument to another function and called later.

function getData(callback: () => void): void {
    console.log("Getting data...");

    callback();
}

function displayData(): void {
    console.log("Data received!");
}

getData(displayData);

How it works:

  1. getData() receives displayData as a callback.
  2. It prints "Getting data...".
  3. It calls callback(), which executes displayData().

2. Promise example

A Promise represents the eventual success or failure of an asynchronous operation.

A promise has three states:

  • pending — the operation is still in progress.
  • fulfilled — operation completed successfully.
  • rejected — operation failed.
function getData(): Promise<string> {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("Hello TypeScript");
        }, 2000);
    });
}

getData()
    .then((data: string) => {
        console.log(data);
    })
    .catch((error: Error) => {
        console.log(error);
    });

How it works:

  • new Promise() Creates a promise.
  • resolve() indicates success.
  • reject() indicates failure.
  • .then() handles a successful result.
  • .catch() handles a rejection.

Real-world Playwright example

Playwright uses promises extensively, so we use await with browser operations.

import { test, expect } from '@playwright/test';

test('Verify page title', async ({ page }) => {
    await page.goto('https://example.com');

    await expect(page).toHaveTitle(/Example Domain/);

    console.log('Title verified successfully');
});
  • page.goto() returns a promise.
  • await waits for navigation to complete.
  • expect() verifies the page title asynchronously.

Remember: A callback is a function passed to another function. A promise represents an asynchronous result. In modern TypeScript and Playwright, promises with async/await are commonly used because they make asynchronous code easier to read.


Rest operator and the Spread operator in TypeScript

1. Rest operator (...remaining)

The Rest operator collects the remaining elements into an array.

let numbers = [10, 20, 30, 40];

let [first, second, ...remaining] = numbers;

console.log(first);
console.log(second);
console.log(remaining);

How it works:

  • first receives 10.
  • second receives 20.
  • ...remaining collects the leftover elements into [30, 40].

This example uses array destructuring with the Rest operator.

2. Spread operator (...fruits)

The Spread operator expands the elements of an array into another array or expression

let fruits = ["Apple", "Banana", "Mango"];

let newFruits = [...fruits];

console.log(newFruits);
Here, ...fruits expands the elements of fruits into a new array. newFruits is a shallow copy of the original array.

Easy trick to remember

  • Rest = Collect the remaining values.
  • Spread = Expand the existing values.

Closures in TypeScript

A closure is created when an inner function remembers and can access variables from its outer function, even after the outer function has finished executing.

In simple words, a closure remembers the variables of its outer function.

The returned function remembers the same count variable between calls. It doesn’t reset to 0 every time.

function counter() {
    let count: number = 0;

    return function () {
        count++;
        console.log(count);
    };
}

let c1 = counter();

c1();
c1();
c1();
Output
1
2
3

Array Methods in TypeScript: map(), filter(), reduce(), forEach(), find()

1. map() — Transform every element

map() creates a new array by applying a function to every element.

let numbers: number[] = [10, 20, 30, 40, 50];

let result = numbers.map(num => num * 2);

console.log(result);

2. filter() — Select matching elements

filter() creates a new array containing only elements that satisfy a condition.

let numbers: number[] = [10, 20, 30, 40, 50];

let result = numbers.filter(num => num > 25);

console.log(result);

3. reduce() — Calculate a single result

reduce() processes the array to produce one accumulated result, such as a sum or total.

let numbers: number[] = [10, 20, 30, 40, 50];

let result = numbers.reduce((total, num) => total + num, 0);

console.log(result);

4. forEach() — Perform an action for every element

forEach() executes a callback for each array element. It does not return a new array.

let numbers: number[] = [10, 20, 30];

numbers.forEach(num => {
    console.log(num);
});

5. find() — Find the first matching element

find() returns the first element that satisfies the condition. If nothing matches, it returns undefined.

let numbers: number[] = [10, 20, 30, 40, 50];

let result = numbers.find(num => num > 25);

console.log(result);