agyanadda@gmail.com

JS Arrays

Arrays and Objects 1 min read Updated Dec 1, 2026 Topic 20 of 38

An array stores a list of values in one variable.

const fruits = ['Apple', 'Mango', 'Banana'];

Read and change

  • fruits[0] → 'Apple' (index starts at 0)
  • fruits.length → 3
  • fruits[1] = 'Grapes'; changes an item
  • Last item: fruits[fruits.length - 1] or fruits.at(-1)

Add and remove

Method Does
push(x) add to the end
pop() remove from the end
unshift(x) add to the start
shift() remove from the start
splice(i, n) remove n items at index i

Check

Array.isArray(value) tells you if something is an array (typeof says "object").

Example

Example — Shopping list HTML
<input id="item" placeholder="Add item">
<button onclick="addItem()">Add</button>
<button onclick="removeLast()">Remove last</button>
<ol id="list"></ol>

<script>
  const items = ['Milk', 'Bread'];

  function render() {
    document.getElementById('list').innerHTML =
      items.map(i => `<li>${i}</li>`).join('');
  }
  function addItem() {
    const input = document.getElementById('item');
    if (input.value.trim()) items.push(input.value.trim());
    input.value = '';
    render();
  }
  function removeLast() {
    items.pop();
    render();
  }
  render();
</script>

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which method adds an item to the end of an array?

Exercise 2 Fill in the Blank

The first item of an array is at index ___.

Exercise 3 True / False

An array can hold values of different types.

Frequently Asked Questions

Use the spread syntax: const copy = [...original]; Writing const copy = original only copies the reference.