Execute Program

JavaScript Arrays: Basics

Welcome to the Basics lesson!

The basics of JavaScript arrays: retrieving elements with "someArray[index]" and storing elements with "someArray[index] = someValue".

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

  • This course assumes that you know some basic JavaScript concepts. Here's a list of concepts that we use but don't explain:

    • null and undefined.
    • Variable definitions with let and const.
    • Conditionals (if) and ternary conditionals (a ? y : b).
    • C-style for loops: for (let i=0; i<10; i++) { ... }.
    • Regular functions: function f() { ... }.
    • Arrow functions: const f = () => { ... }.
  • We cover many of these concepts in our Modern JavaScript course. You can also look them up as you go!

  • This course is intended for both beginners and experienced programmers. It begins with the basics of arrays, but moves on to cover all array methods, including edge cases and more advanced use cases.

  • Arrays are sequences of values that have a specific order and a length.

  • >
    ['a', 'b', 'c'].length;
    Result:
    3Pass Icon
  • >
    [].length;
    Result:
    0Pass Icon
  • Each element in the array gets a sequential index, starting at 0. (We say that arrays are "zero-indexed".) We can retrieve an element by providing its index in [square brackets].

  • >
    const strings = ['a', 'b', 'c'];
    strings[0];
    Result:
    'a'Pass Icon
  • >
    const strings = ['a', 'b', 'c'];
    strings[2];
    Result:
    'c'Pass Icon
  • If we try to access an index that's not in the array, we get undefined.

  • >
    const strings = ['a', 'b', 'c'];
    strings[14];
    Result:
    undefinedPass Icon
  • After we've accessed an element with [], we can assign it a new value with =.

  • >
    const strings = ['a', 'b', 'c'];
    strings[2] = 'x';
    strings;
    Result:
    ['a', 'b', 'x']Pass Icon
  • In some languages, an array can only contain elements of a single type. However, JavaScript arrays can contain a mix of numbers, strings, objects, and even other arrays.

  • >
    const kitchenSink = ['a', 42, {name: 'Amir'}, ['Betty']];
    kitchenSink[3];
    Result:
    ['Betty']Pass Icon
  • When arrays contain other arrays, we can access elements by providing an index for each array in order, like someArray[1][0]. An array containing arrays is sometimes called a "two-dimensional" array. For example, we might use a two-dimensional array to represent cartesian coordinates in a plane.

  • >
    const linePath = [[1, 3], [2, 4], [8, 14]];
    const point1 = linePath[1];
    point1[0];
    Result:
  • >
    const linePath = [[1, 3], [2, 4], [8, 14]];
    linePath[1][0];
    Result:
    2Pass Icon
  • >
    const linePath = [[1, 3], [2, 4], [8, 14]];
    linePath[2][1];
    Result:
    14Pass Icon