What is array in TS point by point with example of code

 Sure, here are the details of arrays in TypeScript along with an example of code:

  1. Declaration: An array is declared using square brackets [] and the type of the elements enclosed in angle brackets <>.
  2. typescript
    let arr: number[]; // Declaring an array of numbers let arr2: string[]; // Declaring an array of strings
    1. Initialization: You can initialize an array with values using the following syntax:
    typescript
    let arr: number[] = [1, 2, 3]; // Initializing an array of numbers with three elements let arr2: string[] = ["apple", "banana", "cherry"]; // Initializing an array of strings with three elements
    1. Accessing Elements: You can access the elements of an array using their index. The index starts from zero.
    typescript
    let arr: number[] = [1, 2, 3]; console.log(arr[0]); // Output: 1 console.log(arr[1]); // Output: 2 console.log(arr[2]); // Output: 3
    1. Array Methods: TypeScript provides several built-in methods for arrays, including:
    • push: Adds an element to the end of the array.
    • pop: Removes and returns the last element of the array.
    • shift: Removes and returns the first element of the array.
    • unshift: Adds an element to the beginning of the array.
    • splice: Removes or replaces elements in the array at a specified position.
    typescript
    let arr: number[] = [1, 2, 3]; arr.push(4); // Adds 4 to the end of the array console.log(arr); // Output: [1, 2, 3, 4] arr.pop(); // Removes and returns 4 from the end of the array console.log(arr); // Output: [1, 2, 3] arr.shift(); // Removes and returns 1 from the beginning of the array console.log(arr); // Output: [2, 3] arr.unshift(0); // Adds 0 to the beginning of the array console.log(arr); // Output: [0, 2, 3] arr.splice(1, 1, 4, 5); // Removes 1 element from position 1 and inserts 4 and 5 console.log(arr); // Output: [0, 4, 5, 3]
    1. Iteration: You can use loops like for and while to iterate over the elements of an array.
    typescript
    let arr: number[] = [1, 2, 3]; for (let i = 0; i < arr.length; i++) { console.log(arr[i]); } // Output: // 1 // 2 // 3

    In summary, arrays in TypeScript are a powerful tool for storing and manipulating collections of elements. They are flexible, easy to use, and provide a wide range of built-in methods for common array operations.

Post a Comment

0 Comments