Back to subject
JavaScript/Arrays

Manage a List of Items

Practical lesson

Let's trace this array from its creation to its final displayed state.

const fruits = ["apple", "banana", "cherry"]; creates an array with three items, at indexes 0, 1, and 2 respectively "apple" is index 0, "cherry" is index 2.

fruits.push("date"); adds "date" to the end of the array, in place the array now has four items: ["apple", "banana", "cherry", "date"], and its length has grown from 3 to 4.

fruits.join(", ") turns the whole array into a single readable string, with ", " placed between each item this is different from just inserting the array directly, which would display it in a less readable default format.

The final output shows all four fruits joined together, "apple" as the first item (fruits[0]), and a total of 4 every piece of that confirms the push actually modified the original array, rather than creating a separate new one.

Try it yourself
Code

Starter example

Code
<script>
  const fruits = ["apple", "banana", "cherry"];
  fruits.push("date");
  document.body.innerHTML = `
    <p>All fruits: ${fruits.join(", ")}</p>
    <p>First: ${fruits[0]}</p>
    <p>Total: ${fruits.length}</p>
  `;
</script>
Live preview