Basics of Javascript · Array · fill() (method)

Jakub Korch
Nerd For Tech
Published in
5 min readDec 22, 2023

This article is a transcript of my free youtube series about basics of web development. If you prefer watching over reading, feel free to visit my channel “Dev Newbs”.

Hello my fellow developers! New day is ahead of us and there is another method from the Array object, ready to be presented to you. This time, we are talking about the fill() method and I am sure you will have many use cases to utilize it in your code once you get to know it.

The method fill() changes all elements within a range of indices in an array to a static value. The result of filling is a modified original array. The method itself has three variations depending on used arguments. The mandatory first one is the value to fill the array with. You can optionally add a start position argument and end position argument. Start position is inclusive, while end position is exclusive. Let’s see it in examples first.

// Example 1
// basic usage

console.log("EXAMPLE 1");
console.log("--------------------------------------------------");

let letters = ["a", "b", "c"];

// fill all with "x" - 1 argument
console.log(letters.fill("x"));
// returns ['x', 'x', 'x']

let numbers = [1,2,3,4,5,6];

// fill all with number 8 starting at index 2 - 2 arguments
console.log(numbers.fill(8, 2));
// returns [1, 2, 8, 8, 8, 8]

let greetings = ["hello", "ola", "ciao", "hallo", "konichiwa", "ni hao", "namaste"];

// fill all with "bonjour" starting at index 1, end index 5 - 3 arguments
console.log(greetings.fill("bonjour", 1, 5));
// returns ['hello', 'bonjour', 'bonjour', 'bonjour', 'bonjour', 'ni hao', 'namaste']

The first example with letters of the alphabet shows us that we can replace all the values or rather fill the whole array with specified value. In our case it was the letter “x”.

The second example with numbers showcases the second argument, which is optional and specifies the index from which you should start filling your array with provided value. As we see in the result, it filled the array with number 8 starting at index 2.

The last example uses both start and end index positions and replaces the strings in the greetings array. As we see, the start index is included in the filling process, while the end index is not.

The fill() method is very similar to an at() method, in a sense that it also allows for the negative indexes to be used. Negative index is transformed into normalized one using following conditions:

  • if end < start after normalization, nothing is filled
  • if end < 0, then index = end + array.length
  • if end < — array.length, then index = 0
  • if end >= array.length, then index = array.length

The last condition is the same as if the end is omitted completely — it fills everything until the end of the array. Now let’s see some examples of this behavior in the second example set.

// Example 2
// negative values

console.log("EXAMPLE 2");
console.log("--------------------------------------------------");

letters = ["a","b","c", "d", "e"];

// start, end less than zero - normalized to start 1, end 3
console.log(letters.fill("z", -4, -2));
// returns ['a', 'z', 'z', 'd', 'e']

numbers = [1,2,3,4,5,6];

// -3 after normalization is 3, end < start - no index filled
console.log(numbers.fill(10, 4, -3));
// returns [1, 2, 3, 4, 5, 6]

greetings = ["hello", "ola", "ciao", "hallo", "konichiwa", "ni hao", "namaste"];

// end more than array length - end equals array.length
console.log(greetings.fill("bonjour", 2, 7));
// returns ['hello', 'ola', 'bonjour', 'bonjour', 'bonjour', 'bonjour', 'bonjour']

The first example shows negative indexes used, which after normalization become positive numbers 1 and 3 respectively. This is aligned with the results we get if you compare it.

The second example with numbers shows that if the end is less than or equal to start, nothing is filled. The number -3 after normalization is 3 and start is at position 4 which results in no changes to the array.

The third example shows that if the end is greater than the array’s length, then the end is equal to it automatically. Everything until the end of the array is filled.

Interesting situation is when instead of a static value, you try to include an actual object. In this case, the reference to the same object fills out all the specified positions.

// Example 3
// filling with objects & empty arrays

console.log("EXAMPLE 3");
console.log("--------------------------------------------------");

letters = ["a", "b", "c", "d"];

console.log(letters.fill({}, 1, 3));
// returns ['a', {}, {}, 'd']

letters[1].letter = "x";

console.log(letters);
// returns ['a', { letter: 'x' }, { letter: 'x' }, 'd']

// filling empty array during declaration
const myArray = Array(5).fill("element");

console.log(myArray);
// returns ['element', 'element', 'element', 'element', 'element']

The first example nicely represents how filling with an object results in multiple references to the same object. Because of that, when you modify one of the elements, you modify all of them.

The second example shows that you can fill the array at the moment of its creation, when it is still just an empty array.

The last thing I will show you today is our good old arrayLike object and its behavior with the method fill().

// Example 4
// array-like object

console.log("EXAMPLE 4");
console.log("--------------------------------------------------");

const arrayLike = {
length: 3,
0: "a",
2: "c",
3: "d"
};

console.log(Array.prototype.fill.call(arrayLike, "z", 1));
// returns {0: 'a', 1: 'z', 2: 'z', 3: 'd', length: 3}

We have our nice object looking like an array, with property length set to value 3. This means, the fill() method will only see numerical properties for indexes 0, 1 and 2. So whatever happened, the property with index 3 will stay intact.

When we actually invoke the method itself, with the argument “z” for the value to be filled with and starting at index 1, we get the arrayLike object updated where the indexes 1 and 2 are modified with the filled value, as should be the case.

Ok, that was method fill() that can fill not only our lonely developer hearts, but also our empty arrays and array-like structures with any value we desire. Thank you for your time spent with me in this video. I will see you soon with the next one.

--

--

Nerd For Tech
Nerd For Tech

Published in Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Jakub Korch
Jakub Korch

Written by Jakub Korch

Web enthusiast, programmer, husband and a father. Wannabe entrepreneur. You name it.

No responses yet