JavaScript

What is the difference between declaring array with Array() or [] in JavaScript?

April 17, 2022

What is the difference between declaring array with Array() or [] in JavaScript?

In this article we will learn the difference between declaring array with Array() or [] in JavaScript, which of these ways is the most efficient?

difference between declaring array with Array cover

Hey you programmer, ok? Let’s learn better how to declare arrays in JavaScript!

There are two ways of declaring arrays in JavaScript, both have the same function and have no difference in implementation.

The only difference, as can be seen, is in the syntax

The Array() way is a way to create an array by instantiating an object directly

When we use [] to create our arrays, we can have the same effect with fewer characters, but the logic done by JS behind the scenes is the same

In the end, an object will be created with a length property, which determines how many elements an array has

And we will also be able to access the indexes in the same way in both variations

See a practical example:

let arrayA = Array(1,2,3);
let arrayB = [1,2,3];
console.log(arrayA); // [1, 2, 3]
console.log(arrayB);// [1, 2, 3]

What happens in practice is that most of the array initializations you will see will be with []

Because it is a shorter syntax and has the same purpose as Array

Curiosity

The Array is an instance of the object, and every object is instantiated as new, but in this case it becomes unnecessary in JavaScript

And if we declare it as new, the object will also be created, and an array will be the final result, with the arguments set as parameters

Conclusion

In this article we learned the difference between declaring array with Array() and []

JavaScript performs the same process in both cases, as long as we have access to the length property in both cases.

Do you want to learn more about JavaScript? Click here!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x