Do you know about the JavaScript Array fill() method?

Hey, what’s up, guys. Here, in this post, again, I will talk about one of the JavaScript Array methods. We will know about the Javascript Array fill() method. So, let’s begin.

What is Array fill() method in JavaScript?

The Array fill() method fills an entire array or part of an array with a value that you pass as a parameter to this method.

This method does not create a new array. It overwrites the original array and returns the modified array, filled with the value you pass as a parameter to this method.

Now let’s see the syntax for it.

array.fill(value, start, end)

A little bit about the parameters.

value – It is the value that you want to fill the array with. It is a required parameter.

start – It is the index from where you want to start filling the specified value. It is an optional parameter. If you don’t specify this parameter then this method will start filling the value from the index 0.

End – It is the index where you want to stop filling the value. The end index is exclusive i.e; the method will fill the specified value until the end-1 index. It is also an optional parameter. If you don’t specify this parameter then this will be length-1 by default.

If you don’t specify the start and end index then the entire array will be filled with the specified value.

Now let’s see an example.

<!DOCTYPE html>

<h1>JavaScript Array fill() method</h1>

<p id="demoId"></p>

const cars = ["Porsche", "BMW", "Audi", "Jaguar", "Tesla"];
document.getElementById("demoId").innerHTML = cars.fill("Bentley",2,4);


Output :

JavaScript Array fill() method


Notice the parameters of the fill() method in the above code. I have passed Bentley as the value to fill and I have passed index 2 as the starting index and index 4 as the end index. So, the fill method will fill the array from index 2 to index 3 (4-1) with the value Bentley.

And this ends the post here.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: