How to populate an empty array in JavaScript?

By IncludeHelp Last updated : January 27, 2024

Problem statement

Given an empty array, write JavaScript code to populate an empty array.

Populating an empty array

To populate an empty array with an element, you can use the Array.fill() method of Array object by passing an element and starting the index from where you want to populate the element.

Consider the below syntax:

Array.fill(element, starting_index)

JavaScript code to populate an empty array

This example populates an empty array by an element "Hello" from the index 0.

// Creating an empty array 
const arr = new Array(5)

// Printing the array before populating
console.log(arr);

// Populating elements to an array
arr.fill("Hello", 0)

// Printing the array before populating
console.log(arr);

Output

The output of the above code is:

[ <5 empty items> ]
[ 'Hello', 'Hello', 'Hello', 'Hello', 'Hello' ]
Note

Never miss to write JavaScript code inside the <script>...</script> tag.

Also Learn: Where to place JavaScript Code?

To understand the above example, you should have the basic knowledge of the following JavaScript topics:

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.