Introduction
In this lab, we will explore how to initialize and fill an array with specific values in JavaScript. We will use the Array() constructor and the Array.prototype.fill() method to create and populate the array. By the end of the lab, you will have a deeper understanding of how to create and manipulate arrays in JavaScript.
Function to Initialize an Array with Specified Values
To start practicing coding, open the Terminal/SSH and type node.
This function initializes an array with the specified values:
- Use the
Array()constructor to create an array of the desired length. - Use
Array.prototype.fill()to fill it with the desired values. - If no value is specified, it defaults to
0.
const initializeArrayWithValues = (length, value = 0) =>
Array(length).fill(value);
Example usage:
initializeArrayWithValues(5, 2); // [2, 2, 2, 2, 2]
Summary
Congratulations! You have completed the Initialize Array With Values lab. You can practice more labs in LabEx to improve your skills.