Execute Program

JavaScript Arrays: New and Fill

Welcome to the New and Fill lesson!

The "new and fill" technique lets us initialize a JavaScript array to a fixed length with all elements set to the same value.

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • The .fill method replaces all of an array's existing values with one value.

  • >
    const a = [1, 2];
    a.fill(3);
    Result:
  • >
    const a = ['a', 'b', 'c'];
    a.fill('d');
    Result:
    ['d', 'd', 'd']Pass Icon
  • What if we don't know how many "d"s we need in advance? First, we can create an array of a given size.

  • >
    const size = 1 + 2;
    const arr = new Array(size);
    arr.length;
    Result:
    3Pass Icon
  • There's nothing in that array yet. If we ask for an element, we'll get undefined.

  • >
    const size = 1 + 2;
    const arr = new Array(size);
    arr[0];
    Result:
    undefinedPass Icon
  • Now that we created an array with a defined size, we can fill it with values. new Array and .fill are commonly used together for this exact reason.

  • >
    const size = 1 + 2;
    new Array(size).fill('d');
    Result:
    ['d', 'd', 'd']Pass Icon
  • Now we can create a dynamically-sized filled array.

  • >
    function newAndFill(size, value) {
    return new Array(size).fill(value);
    }
    newAndFill(2, 'd');
    Result:
    ['d', 'd']Pass Icon
  • Here's a concrete example of how we might use this technique. The progress bar at the top of this lesson is made of many divs. As the developers of Execute Program itself, we know how many paragraphs and code examples exist in the lesson. We create that many divs to form the progress bar. This is done using the new Array(...).fill(...) method shown here!