Open In App

Different ways to populate an array in JavaScript

Last Updated : 07 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Let’s understand the different ways to populate an array in JavaScript. Populating an array means filling an array data structure with a set of values. 

These are the following ways to populate an array:

Method 1: Using Array literal notation

In JavaScript, an array literal notation is a way of creating an array by listing its elements inside square brackets, separated by commas. Using the array literal notation is a convenient method of populating an array with initial values. You can add as many values as you want, and you can mix and match different types of values.

Syntax:

const array = [item1, item2, ...];

Example: In this example, we will be adding elements in the array directly using square brackets [].

Javascript




// Declaring and initializing arrays
let nums = [1, 2, 3, 4, 5];
let names = ["Rahul", "Raju", "Rohit", "Anurag"];
     
// Printing both the array
console.log("nums: ", nums);
console.log("names: ", names);


Output:

nums:  [ 1, 2, 3, 4, 5 ]
names:  [ 'Rahul', 'Raju', 'Rohit', 'Anurag' ]

Method 2: Using a for loop

You can use a for loop to populate an array with elements. Determine how many elements you want in the array. This could be a fixed number or a variable that’s determined at runtime. Use a for loop to iterate over the desired number of elements, adding each one to the array using the push() method.

Syntax:

const arrayNumbers = [];
for (Initialization; Condition; Increment/Decrement) {
    arrayNumbers.push(items);
}

Example: In the given example, we are creating an array of even numbers from 1 to 10 using a for a loop.

Javascript




const evenNumbers = [];
for (let i = 2; i <= 10; i += 2) {
    evenNumbers.push(i);
}
console.log("Even numbers: " + evenNumbers);


Output

Even numbers: 2,4,6,8,10

Method 3: Using the fill() Method

The fill method in JavaScript is a method that is used to populate an array with a static value. It accepts two arguments: the first argument is the value that will be used to fill the array, and the second argument is the starting index from where the filling process will start.

The fill method is useful in situations where we need to initialize an array with a default value or when we need to reset the values of an array to a specific value.

Syntax:

const zeros = new Array(size_array).fill(item);

Example: In the given example, we are creating an array of 0s of size 5 using the fill method.

Javascript




const zeros = new Array(5).fill(0);
console.log("Zeros: " + zeros);


Output

Zeros: 0,0,0,0,0

Method 4: Using the from() Method

The from() method in JavaScript is a method of populating an array. It creates a new array instance from an array-like or iterable object. The from() method returns a new array instance that contains the elements of the original array-like or iterable object.

An array-like object is an object that has a length property and can be indexed like an array, but it may not have all the methods that an array has

Syntax:

const array_ = [some array values];
const new_array = Array.from(array_);

Example: In the given example we are creating an array from a string.

Javascript




const str = "hello";
const chars = Array.from(str);
console.log(
    "New array created using elements of str: "
    + chars
);


Output

New array created using elements of str: h,e,l,l,o

Method 5: Using the map() Method

The map() method in JavaScript is a higher-order function that is used to iterate over an array and return a new array with modified elements based on a given function. The map() method applies the callback function to each element of the array in order and creates a new array with the results. The original array is not modified.

Syntax:

const array_ = [item1, item2, ....];
const squares = numbers.map(item => item * item);

Example: In this example, we take an array and create a new array using the map() method whose elements are squares of the existing array.

Javascript




const numbers = [1, 2, 3, 4, 5];
const squares =
    numbers.map((num) => num * num);
 
console.log("Original Array: ", numbers);
 
console.log("New array created by squaring "
    + "the elements ", squares);


Output

Original Array:  [ 1, 2, 3, 4, 5 ]
New array created by squaring the elements  [ 1, 4, 9, 16, 25 ]

Method 6: Using Spread Operator

The Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 value is expected. It allows us the privilege to obtain a list of parameters from an array. 

Syntax:

let variablename1 = [...value];

Example: In this example, we will use the spread operator for filling the array.

Javascript




let populateArray = [...new Array(5)].map(() => 0);
 
console.log(populateArray);


Output

[ 0, 0, 0, 0, 0 ]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads