Coding with JavaScript For Dummies
Book image
Explore Book Buy On Amazon

Not only can you store arrays inside of arrays with JavaScript, you can even put arrays inside of arrays inside of arrays. This can go on and on. An array that contains an array is called a multidimensional array. To write a multidimensional array, you simply add more sets of square brackets to a variable name. For example:

var listOfLists[0][0];

Multidimensional arrays can be difficult to visualize when you first start working with them.

A pictorial representation of a multidimensional array.
A pictorial representation of a multidimensional array.

You can also visualize multidimensional arrays as hierarchal lists or outlines. For example:

Top Albums by Genre

  1. Country

    Johnny Cash:Live at Folsom Prison

    Patsy Cline:Sentimentally Yours

    Hank Williams:I’m Blue Inside

  2. Rock

    T-Rex:Slider

    Nirvana:Nevermind

    Lou Reed:Transformer

  3. Punk

    Flipper:Generic

    The Dead Milkmen:Big Lizard in My Backyard

    Patti Smith:Easter

Here is a code that would create an array based on what you see above:

var bestAlbumsByGenre = []
bestAlbumsByGenre[0] = "Country";
bestAlbumsByGenre[0][0] = "Johnny Cash:Live at Folsom Prison"
bestAlbumsByGenre[0][1] = "Patsy Cline:Sentimentally Yours";
bestAlbumsByGenre[0][2] = "Hank Williams:I’m Blue Inside";
bestAlbumsByGenre[1] = "Rock";
bestAlbumsByGenre[1][0] = "T-Rex:Slider";
bestAlbumsByGenre[1][1] = "Nirvana:Nevermind";
bestAlbumsByGenre[1][2] = "Lou Reed:Tranformer";
bestAlbumsByGenre[2] = "Punk";
bestAlbumsByGenre[2][0] = "Flipper:Generic";
bestAlbumsByGenre[2][1] = "The Dead Milkmen:Big Lizard in my Backyard";
bestAlbumsByGenre[2][2] = "Patti Smith:Easter";

About This Article

This article is from the book:

About the book authors:

Chris Minnick is an accomplished author, trainer, and web developer who has worked on web and mobile projects for both small and major businesses. Eva Holland is an experienced writer and trainer who has designed and taught online, in-person, and video courses. They are cofounders of WatzThis?

This article can be found in the category: