How to Create an Array Containing 1…N

In this tutorial, you are going to learn about creating a JavaScript Array that contains 1 through to n.

Let's create a new array with a specified length. The constructor sets the length property of the Array to the given length, without setting the keys.

Next, when you want to use it, for example, un-optimized do the following:

let arr = new Array(10); // create an empty array with a length 10
for (let i = 0; i < arr.length; i++) {
  console.log('Item: ' + (i + 1) + '  of   ' + arr.length);
}
The new Array does not create a 10 element array. It creates an empty array with length 10. That's why forEach() and map() methods won't be applied in such cases.

Let's discuss another way of solving this problem. You can do the following:

let n = 10;
let arr = Array.apply(null, {
  length: n
}).map(Number.call, Number);
console.log(arr);
let n = 10;
let arr = Array.apply(null, {
  length: n
}).map(Function.call, Math.random)
console.log(arr);

Number.call(undefined, n) is equal to Number(n) that returns n.

Array.apply(null, [undefined, undefined, undefined]) is equal to Array (undefined, undefined, undefined), which initializes three-element array and assigns undefined to each element.

Now let's generalize that to n elements. The Array() works like this:

function Array() {
  if (arguments.length == 1 &&
    'number' === typeof arguments[0] &&
    arguments[0] >= 0 && arguments &&
    arguments[0] < 1) {
    return […]; // array of length arguments[0]
                // generated by native code
  }
  let arr = [];
  for (let i = 0; i < arguments.length; i++) {
    arr.push(arguments[i]);
  }
  return arr;
}

Now let’s call Array.apply(null, { length: n }):

function Array() {
  let a = [];
  for (let i = 0; i < /* arguments.length = */ n; i++) {
    a.push( /* arguments[i] = */ undefined);
  }
  return a;
}

Now we have an n-element array where each element is set to undefined.

When you invoke .map(callback, thisArg) on it, it will set each element to the result of callback.call(thisArg, element, index, array).

Both Array.apply(null, {length: n}) and Array(n) expressions result an n-element array of undefined elements. According to the map() documentation, the first expression will set each element to undefined, whereas in the second expression, each element was never set.

The callback is called only for indexes of the Array which have assigned values, thus Array(n) is not productive; Array(n).map(Number.call, Number) would result in an uninitialized array of length n.

The Array() Constructor

The Array() constructor creates Array objects. A JavaScript array is created with the given elements, except in the case where a single argument is passed to the Array constructor and is a number. Array length property returns an unsigned, 32-bit integer that specifies the number of elements in the Array.


Do you find this helpful?

Related articles