Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

Is there any difference between the following statements in Javascript?

var multipleValues = [ ];

var multipleValues = new Array();

var multipleValues = Array();

user-image
Question added by Waqas Ahmed , Tech. PM / Software Designer , Aga Khan University Hospital
Date Posted: 2016/10/22
Jonathan de Flaugergues
by Jonathan de Flaugergues , software engineer , Abbeal

var multipleValues = [ ]; is an array literal syntax 

var multipleValues = new Array(); and var multipleValues = Array(); use invokation of Array constructor and both are equivalent because when Array is called as a function instead of constructor (using new keyword), it creates and initialises a new Array object. (the new keyword is injected).

The result of the three statements is the same. The difference come when an integer is passed as argument. var foo = [3] instantiate an array with a length of 1 with the '3' element and var bar = Array(3) instantiate an array with a length of 3 with 3 elements undefined.

Therefore, prefer the using of literals over constructors object because it's shorter, faster to execute and easier to read.

 

 

Mohd Nadeem Mohd Rehman Mohammed
by Mohd Nadeem Mohd Rehman Mohammed , Software Engineer , Softworx Technologies

First Two are the same but first one is recommended to use for simplicity , readability and execution speed.

More Questions Like This

Do you need help in adding the right keywords to your CV? Let our CV writing experts help you.