TypeScript Array fill() Method
Last Updated :
11 Mar, 2024
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
const numbers: number[] = [1, 2, 3, 4, 5];
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
const names: string[] = ["Pankaj", "Ram", "Shravan"];
const filledNames = names.fill("Guest" as string, 1);
console.log(filledNames);
|
Output:
['Pankaj', 'Guest','Guest']
Share your thoughts in the comments
Please Login to comment...