Bird
Raised Fist0
DSA Typescriptprogramming

Array Declaration and Initialization in DSA Typescript

Choose your learning style10 modes available
Mental Model
An array is a list of boxes where each box holds a value and has a number to find it quickly.
Analogy: Imagine a row of mailboxes, each with a number. You can put letters (values) inside and find any letter by looking at the mailbox number.
[0] -> [ ]  [1] -> [ ]  [2] -> [ ]  [3] -> [ ]  [4] -> [ ]
Dry Run Walkthrough
Input: Declare an array of 5 numbers and initialize with values 10, 20, 30, 40, 50
Goal: Create an array with 5 slots and fill each slot with the given number
Step 1: Declare an array with 5 empty slots
[0] -> [ ]  [1] -> [ ]  [2] -> [ ]  [3] -> [ ]  [4] -> [ ]
Why: We need a place to store 5 numbers
Step 2: Put 10 in slot 0
[0] -> [10]  [1] -> [ ]  [2] -> [ ]  [3] -> [ ]  [4] -> [ ]
Why: Fill the first slot with the first value
Step 3: Put 20 in slot 1
[0] -> [10]  [1] -> [20]  [2] -> [ ]  [3] -> [ ]  [4] -> [ ]
Why: Fill the second slot with the second value
Step 4: Put 30 in slot 2
[0] -> [10]  [1] -> [20]  [2] -> [30]  [3] -> [ ]  [4] -> [ ]
Why: Fill the third slot with the third value
Step 5: Put 40 in slot 3
[0] -> [10]  [1] -> [20]  [2] -> [30]  [3] -> [40]  [4] -> [ ]
Why: Fill the fourth slot with the fourth value
Step 6: Put 50 in slot 4
[0] -> [10]  [1] -> [20]  [2] -> [30]  [3] -> [40]  [4] -> [50]
Why: Fill the fifth slot with the fifth value
Result:
[0] -> [10]  [1] -> [20]  [2] -> [30]  [3] -> [40]  [4] -> [50]
Annotated Code
DSA Typescript
class ArrayExample {
  arr: number[];

  constructor(size: number) {
    this.arr = new Array(size);
  }

  initialize(values: number[]): void {
    for (let i = 0; i < values.length && i < this.arr.length; i++) {
      this.arr[i] = values[i];
    }
  }

  print(): void {
    let output = '';
    for (let i = 0; i < this.arr.length; i++) {
      output += `[${i}] -> [${this.arr[i]}]  `;
    }
    console.log(output.trim());
  }
}

const example = new ArrayExample(5);
example.initialize([10, 20, 30, 40, 50]);
example.print();
this.arr = new Array(size);
Create an array with empty slots for the given size
for (let i = 0; i < values.length && i < this.arr.length; i++) { this.arr[i] = values[i]; }
Fill each slot of the array with the corresponding value, up to the array size
for (let i = 0; i < this.arr.length; i++) { output += `[${i}] -> [${this.arr[i]}] `; }
Build a string showing each index and its value for printing
OutputSuccess
[0] -> [10] [1] -> [20] [2] -> [30] [3] -> [40] [4] -> [50]
Complexity Analysis
Time: O(n) because we assign each of the n elements once
Space: O(n) because we store n elements in the array
vs Alternative: Compared to dynamic resizing or linked lists, fixed-size arrays have faster access but fixed size
Edge Cases
Empty array (size 0)
Creates an array with no slots, print shows nothing
DSA Typescript
this.arr = new Array(size);
Initialize with fewer values than size
Only first few slots get values, rest remain undefined
DSA Typescript
for (let i = 0; i < values.length && i < this.arr.length; i++) { this.arr[i] = values[i]; }
Initialize with more values than size
Only values up to the array size are assigned; extra values are ignored
DSA Typescript
for (let i = 0; i < values.length && i < this.arr.length; i++) { this.arr[i] = values[i]; }
When to Use This Pattern
When you need to store multiple items of the same type in order and access them by position, use arrays because they give fast access by index.
Common Mistakes
Mistake: Trying to assign values to an array before declaring its size
Fix: Declare the array size first using new Array(size) before assigning values
Mistake: Accessing array indexes beyond its declared size
Fix: Ensure loop or assignments stay within array length to avoid undefined slots
Summary
It creates a fixed-size list of values stored in order.
Use it when you want to store multiple items and access them quickly by position.
Think of it as numbered boxes where each box holds one value you can find by its number.

Practice

(1/5)
1. Which of the following is the correct way to declare an array of numbers in TypeScript?
easy
A. const numbers: number[] = [1, 2, 3];
B. const numbers: number = [1, 2, 3];
C. const numbers: array = (1, 2, 3);
D. const numbers = {1, 2, 3};

Solution

  1. Step 1: Understand TypeScript array syntax

    In TypeScript, arrays are declared using the type followed by square brackets, e.g., number[].
  2. Step 2: Check each option's syntax

    const numbers: number[] = [1, 2, 3]; correctly declares an array of numbers. Options A, B, and D use incorrect syntax for arrays.
  3. Final Answer:

    const numbers: number[] = [1, 2, 3]; -> Option A
  4. Quick Check:

    Array declaration with type[] = correct syntax [OK]
Hint: Use type[] to declare arrays in TypeScript [OK]
Common Mistakes:
  • Using type without [] for arrays
  • Using parentheses instead of square brackets
  • Using curly braces instead of square brackets
2. Which of the following is the correct syntax to initialize an empty array of strings in TypeScript?
easy
A. let names = string[];
B. let names: string = [];
C. let names: string[] = [];
D. let names: [] = string;

Solution

  1. Step 1: Identify correct type annotation for empty string array

    To declare an empty array of strings, use string[] as the type and assign an empty array [].
  2. Step 2: Validate each option

    let names: string[] = []; correctly uses let names: string[] = []. Others have syntax errors or wrong type placement.
  3. Final Answer:

    let names: string[] = []; -> Option C
  4. Quick Check:

    Empty array of strings = string[] = correct [OK]
Hint: Use type[] with empty brackets to declare empty arrays [OK]
Common Mistakes:
  • Omitting [] after type for arrays
  • Assigning type incorrectly after =
  • Using invalid syntax like let names = string[];
3. What will be the output of the following TypeScript code?
const arr: number[] = [10, 20, 30];
arr[1] = 50;
console.log(arr);
medium
A. [10, 20, 30]
B. [10, 50, 30]
C. [50, 20, 30]
D. Error: Cannot assign to arr[1]

Solution

  1. Step 1: Understand array element assignment

    Arrays allow changing elements by index. arr[1] changes the second element.
  2. Step 2: Apply the assignment and print

    arr[1] = 50 changes the second element from 20 to 50. Printing arr shows [10, 50, 30].
  3. Final Answer:

    [10, 50, 30] -> Option B
  4. Quick Check:

    Index assignment updates array element [OK]
Hint: Array index starts at 0; arr[1] is second element [OK]
Common Mistakes:
  • Thinking arrays are immutable
  • Confusing index 1 with index 0
  • Expecting syntax error on assignment
4. Identify the error in the following TypeScript array declaration:
let nums: number[] = (1, 2, 3);
medium
A. Array elements must be strings
B. Missing type annotation for nums
C. Using let instead of const
D. Using parentheses instead of square brackets for array initialization

Solution

  1. Step 1: Check array initialization syntax

    Arrays must be initialized with square brackets []. Parentheses () create a comma expression, not an array.
  2. Step 2: Identify the error

    Using (1, 2, 3) does not create an array but evaluates to 3. This is incorrect for array initialization.
  3. Final Answer:

    Using parentheses instead of square brackets for array initialization -> Option D
  4. Quick Check:

    Arrays use [] not () for initialization [OK]
Hint: Use [] for arrays, () is for grouping expressions [OK]
Common Mistakes:
  • Confusing parentheses with brackets
  • Ignoring type annotations
  • Thinking let vs const causes error here
5. You want to declare and initialize a 2D array of numbers with 3 rows and 2 columns, all initialized to zero. Which is the correct TypeScript code?
hard
A. const matrix: number[][] = [[0, 0], [0, 0], [0, 0]];
B. const matrix: number[3][2] = [[0, 0], [0, 0], [0, 0]];
C. const matrix: number[] = [0, 0, 0, 0, 0, 0];
D. const matrix = new Array(3, 2).fill(0);

Solution

  1. Step 1: Understand 2D array declaration in TypeScript

    2D arrays are arrays of arrays, so type is number[][].
  2. Step 2: Check initialization for 3 rows and 2 columns

    const matrix: number[][] = [[0, 0], [0, 0], [0, 0]]; correctly initializes 3 arrays each with 2 zeros. const matrix: number[3][2] = [[0, 0], [0, 0], [0, 0]]; uses invalid syntax. const matrix: number[] = [0, 0, 0, 0, 0, 0]; is 1D array. const matrix = new Array(3, 2).fill(0); creates array with 2 elements, not 2D.
  3. Final Answer:

    const matrix: number[][] = [[0, 0], [0, 0], [0, 0]]; -> Option A
  4. Quick Check:

    2D array = array of arrays with type number[][] [OK]
Hint: 2D arrays use type number[][] and nested brackets [OK]
Common Mistakes:
  • Using number[3][2] which is invalid in TypeScript
  • Confusing 1D and 2D array initialization
  • Using new Array with multiple arguments incorrectly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard