How to declare array in javascript..?
|
I'm just learning JavaScript and it seems like there are a number of ways to declare arrays
|
Javascript
- asked 9 years ago
- G John
1Answer
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