JavaScriptLesson 7 of 16

Arrays

An array is a list of values under one name: songs, products, scores. The items keep their order, and counting starts at zero.

Key points

  • ["a", "b"] is an array, list[0] the first item, list.length the number of items
  • The last item: list[list.length - 1] or list.at(-1)
  • push adds to the end, pop takes from the end, shift from the start, unshift adds to the start
  • includes checks whether a value is there, indexOf finds its position
  • join(", ") glues items into a string; a const array can still change, it just cannot be reassigned

Example

const colors = ["red", "green"];colors.push("blue");console.log(colors);console.log(colors.length, colors[0], colors.at(-1));console.log(colors.includes("green"), colors.indexOf("blue")); const last = colors.pop();console.log(last, colors.join(" + "));

push and pop change the array itself: pop returned "blue" and removed it. join turned what was left into a string with " + " between the items.

Task

How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.

A road trip playlist. Add the song Finale to the end, remove the first one (Intro) and print four lines: Songs: 3, First: Sunrise, Last: Finale and the whole list joined with " | ": Sunrise | Night Drive | Finale.

Output

What your program prints appears here.