JavaScript: Initialize and fill an array with the specified values
JavaScript fundamental (ES6 Syntax): Exercise-213 with Solution
Initialize and Fill Array
Write a JavaScript program to initialize and fill an array with the specified values.
- Use Array.from() to create an array of the desired length, Array.prototype.fill() to fill it with the desired values.
- Omit the last argument, val, to use a default value of 0.
Sample Solution:
JavaScript Code:
// Define a function 'initializeArrayWithValues' that creates an array of length 'n' filled with a specified value 'val'
const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val);
// Test the 'initializeArrayWithValues' function by creating arrays of specified lengths filled with specified values
console.log(initializeArrayWithValues(5, 2));
// Output: [2, 2, 2, 2, 2]
console.log(initializeArrayWithValues(4, 0));
// Output: [0, 0, 0, 0]
Output:
[2,2,2,2,2] [0,0,0,0]
Visual Presentation:
Flowchart:

Live Demo:
See the Pen javascript-basic-exercise-213-1 by w3resource (@w3resource) on CodePen.
For more Practice: Solve these Related Problems:
- Write a JavaScript program that creates an array of a specified length and fills it with a given value.
- Write a JavaScript function that uses Array.fill() to initialize an array with dynamic content.
- Write a JavaScript program that generates an array from a seed value and a filling function.
- Write a JavaScript function that returns an array pre-populated with a repeated pattern of values.
Go to:
PREV : n-Dimensional Array.
NEXT : Range Array in Reverse.
Improve this sample solution and post your code through Disqus
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.