Initialize array with values
JavaScript, Array · Oct 20, 2020

Initializes and fills 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. - Omit the last argument,
val
, to use a default value of0
.
const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val);
initializeArrayWithValues(5, 2); // [2, 2, 2, 2, 2]
Written by Angelos Chalaris
I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.
If you want to keep in touch, follow me on GitHub.