Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Foundations Arrays Creating Arrays

one number in new Array(50) is only = array.length


I understand that the array constructor is not recommended, but I find it interesting that when I pass just one number into the parameter of an array constructor, that number is seen as the length of the array. However when I have 2 elements in my array constructor, it is seen as an array of length 2.

In the code below, I have 50 in the parameter of the array constructor, but what if I want 50 to be a value , and not the length of the array constructor, is it possible with array constructors, or is my only choice an array literal. Cheers!

<!DOCTYPE html> <html lang="en"> <head> <title>JavaScript Foundations: The Math Object</title> <link rel="stylesheet" href="core.css"> <script> var display = new Array( 50, 45); alert(display.length);

var show = new Array( 50);


</head> <body>

</body> </html>

3 Answers

Hi. JavaScript Array Syntax: [element0, element1, ..., elementN] new Array(element0, element1, ..., elementN) new Array(arrayLength) (element0, element1, ..., elementN)

"A JavaScript array is initialized with the given elements, except in the case where a SINGLE ARGUMENT is passed to the Array constructor and that argument is a NUMBER. Note that this special case ONLY applies to JavaScript arrays created with the Array constructor, not array literals created with the bracket syntax." Emphasis mine. These are some of the best resources for you in the future: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array http://Speakingjs.com http://Stackoverflow.com

Adam Moore
Adam Moore
21,956 Points

I believe the way it works is that a single value in the constructor is interpreted as the length of the array, with multiple values each being a value within the array, just like you said. However, to use:

var show = [50];

is really not that bad to have to write. :)

thanks Adam!

Thanks Don!