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 of 0.
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.

More like this

  • JavaScript Array Initialization

    Discover the inner workings of JavaScript arrays and learn about the different ways to initialize them.

    Collection · 9 snippets

  • Initialize mapped array

    Initializes and fills an array with the specified values, using a mapping function.

    JavaScript, Array · Jun 13, 2023

  • Initialize array until

    Initializes and fills an array with values generated by a function, until a condition is met.

    JavaScript, Array · Jun 22, 2023

  • Initialize array while

    Initializes and fills an array with values generated by a function, while a condition is met.

    JavaScript, Array · Jun 20, 2023