Different ways to create an Array in JavaScript.

In most programming languages, A collection of a certain finite number of items is an Array. Or the Sets in the Mathematics.

In JavaScript as well, there are many ways to create arrays. We will be taking a look into some of them to create Arrays.

1 . Using assignment operator

var array = [];
var array2 = [1,2,3,4,5];

2. Using new operator

new Array(length)

  • Creates an array with length set to the number.
  • length > 0 otherwise it will throw error
var arr = new Array(2);
arr; [empty × 2]
arr.length; // 2
arr[0]; undefined
// when we set
arr[3] = 10; //It will increase the array size
[empty × 3, 10]

3. Using Array.from

var arr = Array.from({length : 2});
arr; // [undefined, undefined]
arr[0] = 1; arr[1] = 2;
var arrCopy = Array.from(arr);
arrCopy; // [1,2]

4. Usign Spread operator

var arr =  [1,2,3,4,5]
var array2 = [ ...arr ]
array2; // [1,2,3,4,5]

5. Using Array

Creates a new array with the arguments as items. The length of the array is set to the number of arguments.

var array = Array(1,2,3,4,5);
array; // [1,2,3,4,5]

6. Using Array.of

It is similar to Array constructor . But

  • Array.of(5) → [5]
  • Array(5) → [empty x 5]
var array = Array.of(5);
array; / [5]
var array2 = Array.of(1,2,3,4,5,6, "string");
array2; // [1, 2, 3, 4, 5, 6, "string"]

Related Posts

What are custom events in JavaScript?

Custom events are the events that allow you to decouple the code you want to run after a specific piece of code runs. There are various in-built events…

How to use nested for loop in JavaScript?

We use the for loop statement of JavaScript for repeating a set of statements inside the loop body a specified number of times. A nested for loop, as the…

What are the basic rules for JavaScript parameters?

A JavaScript function is a code that performs a particular task. The function parameters are the name list in the function definition. Parameters are also known as…

How to stop refreshing the page on submit in JavaScript?

Using event.preventDefault() to stop page refresh on form submit In this section, we will see how to use event.preventDefault() to stop page refresh on form submission. The event.preventDefault() restricts the default…

Target a Window Using JavaScript or HTML

TARGET attribute of HTML A link’s opening named frame or window is specified using the Target attribute of the <a> anchor tag. The concluding </a> tag in…

What is the role of deferred scripts in JavaScript?

Since JavaScript is a loosely typed language, you are not required to correctly predict the kind of data that will be kept in a variable. Depending on the information…