Open In App

TypeScript Array fill() Method

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

Return Value

Key Points

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.




// 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.




// 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']
Article Tags :