/

HTML / CSS / JavaScript Tutorial

JavaScript Array method: fill()

[this page | pdf | back links]

The fill() method (when applied to a JavaScript array) sets elements of the array to a specified value.

 

It has the following syntax with the following parameters. It returns an array (the changed array).

 

array.fill(value, start, end)

 

Parameter

Required / Optional

Description

value

Required

The value to fill the array with

start

Optional

The index position where elements start to be filled (default is zero)

end

Optional

The index position where elements stop being filled (default is array.length

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
table,th,tr,td {border: 1px solid black; border-collapse: collapse;}
</style>
</head>
<body>
<table>
<tr>
<th>Example</th>
<th>Resulting value of <code>x</code></th>
</tr>
<tr>
<td><code id="Example"></code></td>
<td><code id="Result"></code></td>
</tr>
</table>

<script>
var h = ["a", "b", "c"];
document.getElementById("Example").innerHTML =
  'var h = ["a", "b", "c"];<br>' +
  'var x = h.fill("d");';
document.getElementById("Result").innerHTML = h.fill("d");

function square(x) {
  return x > 0
}
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodArrayFill() {
  var h = [1, 2, 3]; return !!h.fill;
}


NAVIGATION LINKS
Contents | Prev | Next | JavaScript Arrays


Desktop view | Switch to Mobile