DEV Community

Randy Rivera
Randy Rivera

Posted on

Arrays!

Store Multiple Values in one Variable using JavaScript Arrays

With JavaScript array variables, we can store several pieces of data in one place.

You start an array declaration with an opening square bracket, end it with a closing square bracket, and put a comma between each entry.

  • For example:
var myArray = ["Video Games", 23];
Enter fullscreen mode Exit fullscreen mode

The variable myArray which is an array contains both a string and a number.

Nest one Array within Another Array

You can also nest arrays within other arrays, like so:

var myArray = [["Anime Shows", 36], ["Video Games", 23]];
Enter fullscreen mode Exit fullscreen mode

This is also called a multi-dimensional array.

Access Array Data with Indexes

We can access the data inside arrays using indexes.

Array indexes are the same as bracket notation that strings use, although that instead of specifying a character, they are specifying an entry in the array. Also just like strings, arrays use zero-based indexing, so the first element in an array has an index of 0.

  • For example:
var myArray = [10,20,30];

var myData = myArray[0]; 
Enter fullscreen mode Exit fullscreen mode

The variable myData equals the first value of myArray which is 10.

Here we created a variable called myData and set it to equal the first value of myArray using bracket notation.

Modify Array Data With Indexes

Unlike strings, you can change the entries of arrays.

  • Example:
var myArray = [2,4,6];
myArray[0] = 3;
Enter fullscreen mode Exit fullscreen mode

myArray now has the value [3, 4, 6].

Access Multi-Dimensional Arrays With Indexes

One way to think of a multi-dimensional array, is as an array of arrays. When you use bracket notation to access it, the first set of brackets refers to the entries in the outer-most (the first level) array, and each additional pair of brackets refers to the next level of entries inside.

  • For example:
var arr = [[1,2,3], [4,5,6], [7,8,9], [[10,11,12], 13, 14]];
Enter fullscreen mode Exit fullscreen mode
console.log(arr[3]); // displays [[10,11,12], 13, 14]
console.log(arr[3][0]); // displays [10,11,12]
console.log(arr[3][0][1]); //displays 11
Enter fullscreen mode Exit fullscreen mode

Oldest comments (0)