Files
30-seconds-of-code/snippets/js/s/initialize-array-with-values.md
2023-05-14 12:21:52 +03:00

588 B

title, type, language, tags, author, cover, dateModified
title type language tags author cover dateModified
Initialize array with values snippet javascript
array
chalarangelo flower-portrait-1 2020-10-20T23:02:01+03:00

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 of 0.
const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val);
initializeArrayWithValues(5, 2); // [2, 2, 2, 2, 2]