Languages
[Edit]
EN

JavaScript - fill array with default values (ES6+)

0 points
Created by:
Kadeem-Craig
516

In this article, we would like to show you how to fill array with default values in JavaScript (ES6+).

Quick solution:

// ONLINE-RUNNER:browser;

const array = Array(3).fill(0);

console.log(array); // [ 0, 0, 0 ]

 

Practical example

In this example, we create an array with size 5 and use fill() method to fill all its elements with 1 as default value.

// ONLINE-RUNNER:browser;

const array = Array(5).fill(1);

console.log(array); // [ 1, 1, 1, 1, 1 ]

References

Alternative titles

  1. JavaScript - fill whole array with specified value (ES6+)
  2. JavaScript - create zero filled array
  3. JavaScript - create array with the same element repeated multiple times
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - Arrays (popular problems)

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join