Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Janet Leon
Janet Leon
6,908 Points

How does the length method work in a two dimensional array?

Can someone explain this to me?

2 Answers

Cooper Runstein
Cooper Runstein
11,850 Points

An array is just a collection of objects, so the length method calculates how many objects are in the collection you call it on:

[[1,2],['a','b;]].length //2

the above example is 2, because there are two objects in the collection the array [1,2] and ['a', 'b']. Notice that it doesn't matter what type of objects or the depth of those objects:

[[1,2],[3],5,{key: "value"}].length //4

If you view arrays as containers, length calculates how many objects are directly in that container, if your array is like a box, the length method calculates how many things are directly in that box, any small box within your array is counted once no matter how much is in it.

It returns the amount of rows.

A multi-dimensional array is a array that contains arrays (which in turn may include more arrays). The length of arrays is simply the number of values in the array. But these "values" can actually be arrays, because in JavaScript (as in many modern languages), arrays are treated as values.

I hope this helps.