Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript array best practice to use [] instead of new array?

Tags:

javascript

I read at many tutorials that the current best practices to create a new javascript array is to use

var arr = [] 

instead of

var arr = new Array()

What's the reasoning behind that?

like image 783
AlfaTeK Avatar asked May 31 '10 15:05

AlfaTeK


People also ask

What is the difference between new array and [] JavaScript?

They are fundamentally similar. [] is pretty much shortcut for new Array() , so it is preferable. The former is called an array literal/array shorthand. The latter is an example of using the array constructor, which really does the same thing (the array constructor gets called behind the scenes for the literal).

What is the proper way to declare an array in JavaScript?

Using an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [item1, item2, ...]; It is a common practice to declare arrays with the const keyword.

Which is the proper way to declare an array?

The syntax for declaring an array is: datatype[] arrayName; datatype : The type of Objects that will be stored in the array eg. int , char etc.

Why does changing an array in JavaScript affect copies of the array?

An array in JavaScript is also an object and variables only hold a reference to an object, not the object itself. Thus both variables have a reference to the same object.


2 Answers

It might be because the Array object can be overwritten in JavaScript but the array literal notation cannot. See this answer for an example

like image 170
Russ Cam Avatar answered Sep 19 '22 21:09

Russ Cam


Also note that doing:

var x = [5];

Is different than doing:

var x = new Array(5);

The former creates an initializes an array with one element with value of 5. The later creates an initializes an array with 5 undefined elements.

like image 37
reko_t Avatar answered Sep 18 '22 21:09

reko_t