Tech Junkie Blog: JavaScript Array Deep Dive: Creating Arrays

Friday, December 29, 2017

JavaScript Array Deep Dive: Creating Arrays

Arrays in JavaScripts are a collection of values stored in what are called elements.  Each element is represented by a numeric index that is zero based, meaning the first element of an array starts at index zero.  JavaScript arrays are dynamic and can contain many types of objects including functions.  The useful thing about arrays is that they are a specialized object that contains a variety of built-in methods that are useful in the manipulation of the array.

First let's create an empty array, there are several ways to do this:


  1. var empty = [ ];
  2. var empty = new Array();
  3. var empty = new Array(0);

The first example creates an empty array using the [ ] syntax, the second example creates an empty array by instantiating a new Array object with it's default constructor, then the third example creates an array with the Array constructor passing in the element argument of zero.  If you output the array with console.log(empty) they would all be the same output, an array with zero elements








Now let's create arrays with different types of data:

  1. var numbers = [1,2,3,4];
  2. var stringArray = new Array("USA", "Canada","China");
  3. var objectArray = {firstName: "Jack", lastName:"Johnson", weight:"200lbs"};
The first example is an array of numbers, the second array is an array of strings, and the the third array is an array of object.  If we use the console.log method to output the arrays we will find that the first two arrays has a prototype object of Array, but the last array has a prototype object of Object


        console.log(numbers);
        console.log(stringArray);
        console.log(objectArray);





















If you look at the last array objectArray you will noticed that it's not an array at all its actually an object because it is using the prototype Object.  That's because it is declared as an object with just the { } braces.  To make it into an array you just need to surround it with the [ ] brackets. Like the example below:

var objectArray = [{firstName: "Jack", lastName:"Johnson", weight:"200lbs"}];

Now it's an array of objects










Now let's do something that only JavaScript can do very easily. Let's create a mix array of the three above examples.  Let's call it mixedArray, like the code below:

var mixedArray = [numbers, stringArray, objectArray];

If we output it in the console with console.log(mixedArray) we would see the we get all three arrays in mixedArray.  This is what is called an array of arrays or associative arrays.


,

No comments:

Post a Comment