This post will discuss how to declare and initialize arrays in JavaScript.

There are several ways to declare and initialize arrays in JavaScript. An array is a collection of values that can be accessed by an index. Here are some of the common functions:

1. Using an Array constructor

We can use the Array() constructor to create an array using the new keyword and the Array function. We can pass one or more values as arguments to the function. If only a single value is passed to the Array constructor, an empty array of that length is created, with all its elements undefined. However, if more than one values is passed to the Array constructor, the array is initialized with the given elements. The following example demonstrates this behavior:

Download  Run Code

 
To declare and initialize the array with the specified value, we can use the Array constructor with the fill() function. The fill() function updates all element in an array to a given value and returns the modified array.

Download  Run Code

2. Using an array literal

An array literal is the easiest and most concise way to create an array. We can use square brackets [] to enclose a list of values separated by commas. For example:

Download  Run Code

3. Using Array.from() function

The Array.from() function creates a new array instance from the specified array and optionally map each array element to a new value using a mapping function. To create an array, we can pass an empty object with the length property defined. To initialize it with some value, map each element to a new value. For example:

Download  Run Code

4. Using Array.of() function

The Array.of() static function that creates a new array from a variable number of arguments. It works similarly to the Array constructor, but it always creates an array with the given arguments as elements, regardless of their type or number. For example:

Download  Run Code

 
That’s all about declaring and initializing arrays in JavaScript. Keep in mind that we can use the Array.map() function to create a new array from an old array, with each item of the old array transformed to a new value. The map() function accepts a callback function as an argument and gives back a new array with the results of applying the function to every array element. For example:

Download  Run Code