• support@answerspoint.com

How to declare array in javascript..?

1726
so I want to create an array in javascript and remember two ways of doing it so I just want to know what the fundamental differences are and if there is a performance difference in these two "styles"
 
 

I'm just learning JavaScript and it seems like there are a number of ways to declare arrays

  1. var myArray = new Array()
  2. var myArray = new Array(3)
  3. var myArray = ["apples", "bananas", "oranges"]
  4. var myArray = [3]

1Answer


0

Three Ways to Declare an Array in JavaScript

You can declare JavaScript arrays: by using the array constructor, the literal notation, or by calling methods with array return types.

JAVASCRIPT ARRAY CONSTRUCTOR

We can explicitly declare an array with the JavaScript "new" keyword to instantiate the array in memory (i.e. create it, and make it available).

// Declare an array (using the array constructor)
var arlene1 = new Array();
var arlene2 = new Array("First element", "Second", "Last");

We first declared an empty array. We then assigned three elements to the second array, while declaring it. "new Array()" is the array constructor.

ARRAY LITERAL NOTATION

Below, we use an alternate method to declaring arrays:

// Declare an array (using literal notation)
var arlene1 = [];
var arlene2 = ["First element", "Second", "Last"];

We declared above the exact same arrays as previously; instead of new Array(�), you can use square brackets, optionally enclosing elements. Using square brackets (vs. array constructor) is called the "array literal notation."

IMPLICIT ARRAY DECLARATION

JavaScript also lets you create arrays indirectly, by calling specific methods:

// Create an array from a method's return value
var carter = "I-learn-JavaScript";
var arlene3 = carter.split("-");

We indirectly created an array by using the string split() method; several other JavaScript methods return an array as result. As illustration, the array returned by the split() method is identical to the one declared below.

var arlene4 = new Array("I", "learn", "JavaScript");

  • answered 8 years ago
  • Gul Hafiz

Your Answer

    Facebook Share        
       
  • asked 9 years ago
  • viewed 1726 times
  • active 9 years ago

Best Rated Questions