What is the way of declaring an array in JavaScript? (beginner) -


I'm just learning JavaScript and it seems that there are several ways to declare an array.

    var myArray = new array ()
  1. var myArray = new array (3)
  2. What is their difference, and what are the most preferred ways?

    According to the following two lines are very different:

      var badArray = new Array (10); // creates an empty array of sizes for 10 elements; Good good = [10]; // Creates an array with the first element as 10   

    As you can see that there are two very different things in these two lines if you have more than one item If you wanted to add then bad will start correctly because Javascript will be quite clever then instead of knowing how many elements you want to add, instead you are starting the array.

    What is the author trying to say array (10) creates an array with exactly 10 elements and [10] Creates an array of undefined size with 0th element being 10? Or what does this mean?

    The most preferred method is to always use lexical syntax with the square bracket; Its behavior is predictable for any number, what's more unlike the array , array is not a keyword, and although it is not a real situation, anyone can easily Can overwrite:

      function array () {return []; } Alerts (Array (1, 2, 3)); // An Empty Alert Box   

    However, the big issue is of stability. Any refactoring code can come in this function:

      function fetchValue (n) {var arr = new array (1, 2, 3); Return arr [N]; }   

    As it turns out, only fetchValue (0) is required, so the programmer leaves other elements and breaks the code, because It is now undefined :

      var arr = new array (1);    

Comments