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

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.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

    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.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

    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.


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.