Skip to content

Commit 8d544a8

Browse files
[Term Entry] JavaScript Arrays: fill() (#7347)
1 parent 00e7e6a commit 8d544a8

File tree

1 file changed

+123
-0
lines changed
  • content/javascript/concepts/arrays/terms/fill

1 file changed

+123
-0
lines changed
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
---
2+
Title: '.fill()'
3+
Description: 'Changes all elements within a range of indices in an array to a static value.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Web Development'
7+
Tags:
8+
- 'Arrays'
9+
- 'JavaScript'
10+
- 'Methods'
11+
- 'Range'
12+
CatalogContent:
13+
- 'introduction-to-javascript'
14+
- 'paths/front-end-engineer-career-path'
15+
---
16+
17+
JavaScript's **`array.fill()`** method changes all elements within a range of indices in an [array](https://www.codecademy.com/resources/docs/javascript/arrays) to a static value. It modifies the original array and returns the modified array, making it a mutating method that provides an efficient way to populate array elements with the same value.
18+
19+
## Syntax
20+
21+
```pseudo
22+
array.fill(value, start, end)
23+
```
24+
25+
**Parameters:**
26+
27+
- `value`: The value to fill the array elements with. All elements in the specified range will be set to this exact value.
28+
- `start` (optional): The zero-based index at which to start filling. If negative, it is treated as `array.length + start`. Defaults to `0`.
29+
- `end` (optional): The zero-based index at which to end filling (exclusive). If negative, it is treated as `array.length + end`. Defaults to `array.length`.
30+
31+
**Return value:**
32+
33+
The `.fill()` method returns the modified array with elements filled according to the specified parameters.
34+
35+
## Example 1: Basic Array Filling Using `array.fill()`
36+
37+
This example demonstrates the fundamental usage of the `.fill()` method by replacing all elements in an array with a single value:
38+
39+
```js
40+
// Create an array with different values
41+
const numbers = [1, 2, 3, 4, 5];
42+
43+
// Fill all elements with the value 0
44+
numbers.fill(0);
45+
46+
console.log(numbers);
47+
```
48+
49+
The output of this code is:
50+
51+
```shell
52+
[0, 0, 0, 0, 0]
53+
```
54+
55+
The `.fill()` method replaces every element in the array with the specified value, transforming the original array `[1, 2, 3, 4, 5]` into `[0, 0, 0, 0, 0]`.
56+
57+
## Example 2: Creating Default User Profiles Using `array.fill()`
58+
59+
This example shows how `.fill()` can be used in a real-world scenario to initialize an array of user profile objects with default values:
60+
61+
```js
62+
// Create an array to hold 3 user profiles
63+
const userProfiles = new Array(3);
64+
65+
// Fill with default user profile objects
66+
userProfiles.fill({
67+
name: 'New User',
68+
69+
status: 'inactive',
70+
});
71+
72+
// Update one user's information
73+
userProfiles[0].name = 'John Doe';
74+
userProfiles[0].email = '[email protected]';
75+
76+
console.log(userProfiles);
77+
```
78+
79+
The output of this code is:
80+
81+
```shell
82+
[
83+
{ name: 'John Doe', email: '[email protected]', status: 'inactive' },
84+
{ name: 'John Doe', email: '[email protected]', status: 'inactive' },
85+
{ name: 'John Doe', email: '[email protected]', status: 'inactive' }
86+
]
87+
```
88+
89+
When using objects with `.fill()`, all array elements reference the same object. Modifying one element affects all elements because they share the same reference.
90+
91+
## Codebyte Example: Using `array.fill()` to Initialize Game Board Sections
92+
93+
This example demonstrates using `.fill()` with start and end parameters to initialize specific sections of a game board array:
94+
95+
```codebyte/javascript
96+
// Create a game board with 10 positions
97+
const gameBoard = new Array(10).fill('empty');
98+
99+
// Fill positions 2-5 with player pieces
100+
gameBoard.fill('player1', 2, 6);
101+
102+
// Fill positions 7-8 with obstacles
103+
gameBoard.fill('obstacle', 7, 9);
104+
105+
console.log(gameBoard);
106+
console.log(`Board length: ${gameBoard.length}`);
107+
```
108+
109+
By specifying start and end indices, the `.fill()` method allows precise control over which elements to modify, making it ideal for initializing specific ranges within larger data structures.
110+
111+
## Frequently Asked Questions
112+
113+
### 1. How to fill an array in JS?
114+
115+
Use the `.fill()` method on an existing array: `array.fill(value)`. For new arrays, create them first with `new Array(length)` or `Array(length)`, then apply `.fill()`: `new Array(5).fill('default')`.
116+
117+
### 2. How to fill array with unique values in JavaScript?
118+
119+
The `.fill()` method creates identical values, not unique ones. For unique values, use `Array.from()` with a mapping function: `Array.from({length: 5}, (_, index) => index + 1)` creates `[1, 2, 3, 4, 5]`.
120+
121+
### 3. Does .fill() change the original array?
122+
123+
Yes, `.fill()` is a mutating method that modifies the original array directly. If you need to preserve the original array, create a copy first using `[...array].fill(value)` or `Array.from(array).fill(value)`.

0 commit comments

Comments
 (0)