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


Jeremy Frimond
Jeremy Frimond
14,470 Points

General JS Question on Arrays

When creating an array with the syntax new Array(argument), what is the argument passed to Array?

1 Answer

When using the constructor to create an array (new Array(arg)), there are two possible types of argument(s).

If there is only a single argument, and it's an integer, it will create an array with a length set to that integer:

var myArr = new Array(5);
// output: [undefined, undefined, undefined, undefined, undefined]

If instead you list several arguments, it will create an array and treat those arguments as array elements:

var firstElement = 5;
var secondElement = "text";
var thirdElement;
var myArr2 = new Array(firstElement, secondElement, thirdElement);
// output: [5, "text", undefined]

More info on MDN