Array fill() method with example in JavaScript

JavaScript fill() method: Here, we are going to learn about the fill() method of array in JavaScript.
Submitted by IncludeHelp, on March 02, 2019

JavaScript fill() method

fill() method is used fill the array with a given value.

Syntax:

    array.fill(value, [start_index], [end_index]);

Parameters:

  • value is a static value to be filled in the array.
  • start_index is an optional parameter, it specifies the starting index to fill the array, its default value is 0.
  • end_index is also an optional parameter, it specifies the ending index to fill the array, its default value is array.length.

Return value: None

Example:

    Input:
    var arr = [10, 20, 30, 40, 50];

    Function call:
    arr.fill(0);
    
    Output:
    0,0,0,0,0

JavaScript Code to demonstrate example of Array.fill() method

<html>
<head>
<title>JavaScipt Example</title>
</head>

<body>
	<script>
		var arr = [10, 20, 30, 40, 50];
		document.write("array elements: " + arr + "<br>");
		
		//filling all elements
		arr.fill(0);
		document.write("array elements: " + arr + "<br>");
		
		//filling initial 2 elements with 100
		arr.fill(10, 0, 2);
		document.write("array elements: " + arr + "<br>");

		//filling next 3 elements with 200
		arr.fill(200, 2, 5);
		document.write("array elements: " + arr + "<br>");		
	</script>
</body>
</html>

Output

array elements: 10,20,30,40,50
array elements: 0,0,0,0,0
array elements: 10,10,0,0,0
array elements: 10,10,200,200,200

JavaScript Array Object Methods »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.