Populate an Array

A typical question asked in "History of JavaScript" classes where the teacher mistakenly believes they are teaching programming.


Create an array consisting of ten entries and load the values 0 through 9 into the array.

Now in the real world you'd hard code such a simple array using [0,1,2,3,4,5,6,7,8,9] so let's modify the question slightly and ask for an array of ten thousand entries instead of only ten. This doesn't actually change the expected historical answer but does make it necessary to actually use code to create the answer rather than simply hard coding the array.

Historical Answer:

var a = new Array(10000);
for (var i = 0; i <= a.length; i++) {
a[i] = i;

The obvious reason for asking this question is to test the person's knowledge of how to construct loops in JavaScript. Now while loops are ocassionally useful in JavaScript, there is never a need to use a loop to process a JavaScript array or anything that can be converted into a JavaScript array (except perhaps with really complex JavaScript where an efficiently coded array may be used for efficiency reasons - something that certainly doesn't apply with this particular question where using the loop is actually the least efficient method by far).

JavaScript Answer:

Array.prototype.populate = function(n) {
return Object.keys(Object(0+Array(n)));
var a = [].populate(10000);

By converting an array first to a string and then to an object we end up with an object where the property keys are the exact values this question is looking for and so we can populate an array with the 10000 numbers corresponding to the positions they are in within the array in what is effectively three statements instead of the 20000 statements that the historical solution required.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow