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 JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Adding Data to Arrays

Declaring an array

If I don't know about the data in the array but I know about the size of array. how should i declare it? for eg - In Java int arr[] = new int[10];

2 Answers

It's simple. In JavaScript you do this that way:

var myArray = new Array(10);

Of course you can name your array however you want, new Array() creates an empty array and if you pass integer to it it will create empty array with number of elements. In your case empty array with 10 elements inside.

PS: I don't know about Java but in JavaScript you don't have to set size of an array when declaring it. You can add elements to array on the fly with methods like push and shift.

How can 2-d array be declared?

How can 2-d array be declared?

JavaScript does not have true multi-dimensional arrays (neither does Java for that matter). Instead you can have arrays of arrays, aka jagged arrays. C# has both, see here for some further explanation. The syntax is similar to Java, so you should be able to follow.

Since arrays in JavaScript can grow dynamically, like say an ArrayList in Java, there is not need to set aside memory for your data by declaring that you want to put arrays into an array. Instead, if you already know the data you want to store when you create the variable, you simply type it out:

var matrix = [[1, 2], 
              [3, 4]]

Otherwise you can push/unshift more stuff into your array later on:

matrix.push([5, 6]);