Open In App

What’s the difference between “Array()” and “[]” while declaring a JavaScript array?

Last Updated : 27 Sep, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

Consider the below codes:

var myArray = new Array(5);

and

var myArray = [5];

Though these two lines might appear the same, but it is not the case.

Consider the below explanations:
Case 1: var myArray = new Array(5)

  • This method is used to define an array of length 5. The parameter passed here ‘5’ is an argument that defines the initial length of the array to be made. Hence any value can be passed to get the array of that length using this code.




    // Write Javascript code here
    //Creates an array of 5 undefined elements 
    var arr = new Array(5); 
      
    alert(arr.length);

    
    

    Output:

    5
    
  • Another advantage of using this method is that it creates the required size of the array beforehand in the stack. This, in turn, helps to avoid StackOverflow error.

Case 2: var myArray = [5]

  • This method is used to define an array of with the values where the length of the array is equal to the number of values passed to in the square brackets. The parameter passed here ‘5’ is the value for myArray’s 0th element, i.e. myArray[0] = 5.




    // Write Javascript code here
    //Creates an array of 5 undefined elements 
    var arr = [5]; 
      
    alert(arr[0]);
    alert("\n"+arr.length);

    
    

    Output:

    5
    1
    
  • This method does not create the required size of the array beforehand in the stack. Hence this method needs the memory to be defined every time the array expands, which in turn can lead to StackOverflow error.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads