The fill() method in TypeScript is utilized to replace all the elements within an array with a fixed value. This action alters the array itself and returns the updated version. This method is helpful for 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.
Example 1: Filling a Portion of an Array with Zeros
In this example, we will fill a portion of an array with zeros.
let numbers: number[] = [1, 2, 3, 4, 5];
numbers.fill(0, 1, 4);
console.log(numbers);
Output:
[1, 0, 0, 0, 5]
Example 2: Filling a String Array with "Guest" from a Specific Index
In this example, we will fill a string array with the value "Guest" starting from a specific index.
let guests: string[] = ['Pankaj', 'Rahul', 'Ankit'];
guests.fill('Guest', 1);
console.log(guests);
Output:
['Pankaj', 'Guest', 'Guest']