Home / Programs / Typescript - Finding Array Length
🚀 Programming Example

Typescript - Finding Array Length

👁 118 Views
💻 Practical Program
📘 Step Learning

📌 Information & Algorithm

Typescript - Finding Array Length

Create a function "arrLength" that takes an array as input that accept any type of array, calculate the number of elements present in it and return it. Use the function to find out the length of the array. Define proper types as and when required - return type and the param type of the function argument should be mentioned.

Given Input 1:

["hi", "there"]

Expected Output:

Sample Output 1: 2

Given Input 2:

Sample Input 2: [1,5,4]

Expected Output:

Sample Output 2: 3

💻 Program Code

function arrLength<T>(arr: T[]): number {
  return arr.length;
}
                        

🖥 Program Output

// Sample Input 1
const array1: string[] = ["hi", "there"];
const result1: number = arrLength(array1);
console.log("Sample Output 1:", result1); // Output: 2

// Sample Input 2
const array2: number[] = [1, 5, 4];
const result2: number = arrLength(array2);
console.log("Sample Output 2:", result2); // Output: 3
                            
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.