Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages of using [] over new Array() in JavaScript

Tags:

javascript

What are the advantages of using

var foo = []; 

over using

var bar = new Array();

i've been told to use [] over new Array() but never with much explanation

like image 527
Alex Avatar asked Mar 25 '10 15:03

Alex


People also ask

What does [] in JavaScript mean?

It is shorthand for empty array. Same as new Array(). Also {} is an empty object. Objects are like hashtables in Js so you can use it as a dictionary. Copy link CC BY-SA 2.5.

What is [] vs {} in JS?

[] is declaring an array. {} is declaring an object. An array has all the features of an object with additional features (you can think of an array like a sub-class of an object) where additional methods and capabilities are added in the Array sub-class.

What are the advantages of structure over array?

Advantages of Structure over Array:The structure can store different types of data whereas an array can only store similar data types. Structure does not have limited size like an array. Structure elements may or may not be stored in contiguous locations but array elements are stored in contiguous locations.

What is the advantage of using arrays over multiple variables?

1) Array stores data elements of the same data type. 2) Maintains multiple variable names using a single name. Arrays help to maintain large data under a single variable name. This avoid the confusion of using multiple variables.


2 Answers

The main reason to use [] as opposed to new Array() is the arguments you pass. When you use new Array(10), you create an empty array with 10 elements, but when you use [10], you create an array with one element who's value is 10. Since this is generally the information most programmers want to pass to an array (as arrays are dynamic in Javascript), this is generally considered the best practice. Also new Array(10,20) works differently than new Array(10). In this case you have the same effect as [10,20] which is to create an array with 2 elements, 10 and 20. Since this is... strange at best... it's easy to accidentally create an empty array by passing new Array() only one value. [] always has the same effect, so I'd also recommend sticking with it.

like image 117
Chibu Avatar answered Sep 22 '22 01:09

Chibu


  • shorter
  • arguments of Array are confusing (e.g. new Array(10) and new Array("10") are quite different)
like image 20
user187291 Avatar answered Sep 19 '22 01:09

user187291