Home » JavaScript

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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.