find the average of a list of numbers in typescript

To find the average of a list of numbers in TypeScript, you can follow these steps:

  1. Create an array of numbers.
  2. Use a loop to iterate through the array and add up all the numbers.
  3. Divide the sum by the total number of elements in the array to get the average.
const numbers: number[] = [5, 10, 15, 20, 25];

const getAverage = (arr: number[]): number => {
  let sum: number = 0;
  const length: number = arr.length;

  for (let i = 0; i < length; i++) {
    sum += arr[i];

  const avg = sum / length;
  return avg;

console.log(getAverage(numbers)); // Output: 15
311 chars
16 lines

In the code above, we first declare an array of numbers. We then define a function getAverage that takes an array of numbers as an argument and returns the average of the numbers.

Inside the function, we initialize two variables sum and length to 0 and the length of the array, respectively. We then use a for loop to iterate through the entire array and add up each element to the sum variable.

Finally, we calculate the average by dividing the sum by the length of the array and return it. When we call the getAverage function passing the numbers array, we get the output as 15, which is the average of the array.

gistlibby LogSnag