Javascript Arrays

  • for notes comparing arrays and objects & on nesting arrays and objects look in the file


  • lets us group data in a list
  • 0 indexed (or 0 based)
  • comma separated
  • members are mutable --- can be changed
  • can hold any type of data
  • one array can contain multiple types of data
  • have a length property
    • arrayName.length
  • defining empty arrays:
    • let arrayName = []
    • let arrayName = new Array() // not very common
  • accessing elements:
    • arrayName[index]
  • to add new pieces of data just assign the data to an index that doesn't exist yet
    • example:
      let colors = ['red', 'orange', 'yellow'];
      colors[3] = 'green';
      // colors is now ['red', 'orange', 'yellow', 'green']
      // if not sure what the next index is can use the length property
      colors[colors.length] = pink;
      // colors is now ['red', 'orange', 'yellow', 'green', 'pink']
      // can also add to indexes that aren't the next empty index
      colors[10] = 'violet';
      // colors is now ['red', 'orange', 'yellow', 'green', 'pink', undefined x 5, 'violet']
  • if have nested arrays, you can find an element from the inner array by arrayName[outerArrayIndex ][innerArrayIndex]


  • can find list/info of all array methods on MDN


  • push to add the end of an array
    • always knows the last index of the array so it adds in the next index
    • returns the new length of the array when the function is applied
  • pop to remove the last element in an array
    • returns the popped element


  • unshift to add to the front of an array
  • shift to remove the first item in an array
    • returns the removed element


  • takes an argument and attempts to find it in the array --- it returns the index
  • returns -1 if the item is not in the array
  • if it occurs more than once, it returns the first occurrence

includes (ES6)

  • takes an argument and attempts to find it in the array --- it returns a boolean
  • tests with strict equality (no type coercion)


  • to copy parts of an array
  • does not alter the original array, so must save it to a new variable
  • takes two arguments
    • first is the index where the new array starts --- inclusive
    • second is the index where it ends --- not inclusive
  • can also copy the whole array by calling with no arguments


  • make a cut and remove a specific element/s from an array
  • takes two arguments:
    • first is where to make cut --- inclusive
    • second is how many elements to remove


  • used when you want to do something to every item in a list
  • real world usage examples:
    • reddit posts --- comments are saved in array
    • for ToDo list apps
    • blog posts
  • SEE conditionals_and_loops notes for more info

Copyright © 2022