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 Foundations Arrays Creating Arrays

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

Hello!

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);
alert(show.length);


</script>

</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:

<script>
var show = [50];
alert(show.length);
</script>

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

thanks Adam!

Thanks Don!