JavaScript Array fill() and toString()
In this post, we will discuss fill(),toString() methods available in JavaScript Array.
fill()
The fill() method will fill the array with the given element. It takes three parameters. First parameter is the element to be filled, second parameter is specifying the start position and second parameter specifies the end position. If these two parameters are not specified, then entire array is filled with the element.
Syntax:
array_name.fill(element,start,end)
Here, 'array_name' is the name of the array.
Example 1:-
Let us create an array that hold 5 strings and fill first two values with "chemistry".
<html>
<body>
<script>
// Create an array that hold 5 strings.
const subjects =["php","sql","java",".bet","iot"];
document.writeln("Subjects: <br>");
document.writeln(subjects);
document.writeln("<br>");
document.writeln("<br>");
// Fill first two elements in the array with "chemistry".
subjects.fill("chemistry", 0, 2);
document.writeln("Final Subjects: <br>");
document.writeln(subjects);
</script>
</body>
</html>
Output:
Subjects:
php,sql,java,.bet,iot
Final Subjects:
chemistry,chemistry,java,.bet,iot
We can see that first two elements are replaced with "chemistry".
Example 2:-
Let us create an array that hold 5 strings and fill values with "chemistry" without specifying last 2 parameters.
<html>
<body>
<script>
// Create an array that hold 5 strings.
const subjects =["php","sql","java",".bet","iot"];
document.writeln("Subects: <br>");
document.writeln(subjects);
document.writeln("<br>");
document.writeln("<br>");
// Fill elements in the array with "chemistry".
subjects.fill("chemistry");
document.writeln("Final Subects: <br>");
document.writeln(subjects);
</script>
</body>
</html>
Output:
Subects:
php,sql,java,.bet,iot
Final Subects:
chemistry,chemistry,java,.bet,iot
We can see that all the elements in the array are filled with "chemistry".
toString()
The toString() method will return the array of elements to a string. These elements are separated by a comma. It will not take any parameter.
Syntax:
array_name.toString()
Here, 'array_name' is the name of the array.
Example 1:-
Let us create an array that hold 5 strings and convert to string.
<html>
<body>
<script>
// Create an array that hold 5 strings.
const subjects =["php","sql","java",".bet","iot"];
// Convert subjects to string.
document.writeln(subjects.toString());
</script>
</body>
</html>
Output:
php,sql,java,.bet,iot
We can see that the subjects-array is converted to string.