Open In App

TypeScript Array fill() Method

Last Updated : 11 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

fill() method is utilized to replace all the elements within an array, with a fixed value in TypeScript.

This action alters the array itself and gives back the updated version.

This method helps in the easy transformation of an array in TypeScript.

Syntax

array.fill(value[, start[, end]])

Parameters

  • value: The value you want to use for populating the array.
  • start (optional): The index, from where you want to start filling the array (default is 0).
  • end (optional): The index where you want to stop filling the array (default is the length of the array).

Return Value

  • The array that has been modified with the values. It is the array that was filled.

Key Points

  • fill() method does not alter the length of array, and only the content of array.
  • It does not work on array with length=0, as there is no content in array.
  • fill() method is not suitable to be used on strings, as strings are immutable.

Examples of fill() in TypeScript

Let’s see some more examples of array fill() method in TypeScript.

1. Example 1: In this example, we will fill a portion of an array with zeros.

TypeScript




// Here we are defining an array of
// numbers with type annotations
const numbers: number[] = [1, 2, 3, 4, 5];
 
// Here we will fill a portion of the array with zeros
const filledArray = numbers.fill(0 as number, 1, 4);
 
console.log(filledArray);


Output:

[1, 0, 0, 0, 5]

2. Example 2:In this example, we will fill a string array with “Guest” from a specific index.

TypeScript




// Here we are defining a string
// array with type annotations
const names: string[] = ["Pankaj", "Ram", "Shravan"];
 
// Here we will fill the array
// with "Guest" from index 1 onwards
const filledNames = names.fill("Guest" as string, 1);
 
console.log(filledNames);


Output:

['Pankaj', 'Guest','Guest']

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads