← Back to JavaScript series
πŸ—‚οΈ
Objects & Arrays
Intermediate Β· Prerequisite: 06_Objects

07. Arrays Basics

An array is an ordered collection of values accessed by zero-based indices.

arraypushspliceiteration
Duration
⏱ ~1 hour
Level
πŸ“Š Beginner
Prerequisite
🎯 Lecture 6
OUTCOME
An array is an ordered collection of values accessed by zero-based indices.

What you'll learn

  • 1Create arrays and access/modify them by index.
  • 2Understand what `length` actually means.
  • 3Add and remove elements with `push`, `pop`, `shift`, `unshift`.
  • 4Tell `splice` (mutates) and `slice` (returns a new array) apart.
  • 5Iterate arrays with `for...of`.

Overview

An array is an ordered collection of values accessed by zero-based indices.

Core Concepts

1. Creating arrays and indexing

An array is an ordered collection of values accessed by zero-based indices.

javascript
const fruits = ["apple", "banana", "grape"];
console.log(fruits[0]);      // "apple"
console.log(fruits.length);  // 3
fruits[1] = "strawberry";

`length` is one more than the highest index. Setting `fruits.length = 1` truncates the trailing elements.

2. Adding and removing at the ends

`push`/`pop` work at the end; `unshift`/`shift` work at the front. Front operations are slower because every element has to be shifted.

javascript
const arr = [1, 2, 3];
arr.push(4);     // [1, 2, 3, 4]
arr.pop();       // [1, 2, 3]
arr.unshift(0);  // [0, 1, 2, 3]
arr.shift();     // [1, 2, 3]

3. splice vs slice

`splice(start, deleteCount, ...items)` mutates the original. `slice(start, end)` returns a new array, with `end` excluded.

javascript
const nums = [1, 2, 3, 4, 5];
const removed = nums.splice(1, 2, 99); // nums = [1, 99, 4, 5], removed = [2,3]
const copy = nums.slice(1, 3);          // [99, 4]  original untouched

4. Iteration (for...of)

If you don't need the index, `for...of` is the cleanest. If you also need the index, combine it with `entries()`.

javascript
for (const item of fruits) console.log(item);
for (const [i, item] of fruits.entries()) console.log(i, item);

Examples

FileWhat it covers
`01_index.js`Index access and length behavior
`02_push_pop.js`Add/remove methods
`03_splice.js`splice vs slice
`04_iteration.js`for, for...of, forEach

src/01_index.js

javascript
/**
 * Index access and length
 */
"use strict";

const colors = ["red", "green", "blue"];
console.log(colors[0], colors[2]);
console.log("length =", colors.length);

colors[3] = "yellow";
console.log("after add =", colors);

colors.length = 2;
console.log("truncated =", colors);

src/02_push_pop.js

javascript
/**
 * Add/remove methods
 */
"use strict";

const stack = [];
stack.push(1);
stack.push(2);
stack.push(3);
console.log("after push =", stack);

const top = stack.pop();
console.log("pop =", top, "now =", stack);

const q = [1, 2, 3];
q.unshift(0);
console.log("unshift =", q);
const first = q.shift();
console.log("shift =", first, "now =", q);

src/03_splice.js

javascript
/**
 * splice vs slice
 */
"use strict";

const nums = [1, 2, 3, 4, 5];

const removed = nums.splice(1, 2, 99, 100);
console.log("after splice =", nums);
console.log("removed =", removed);

const copy = nums.slice(1, 4);
console.log("slice =", copy);
console.log("nums unchanged =", nums);

src/04_iteration.js

javascript
/**
 * Ways to iterate an array
 */
"use strict";

const items = ["a", "b", "c"];

for (let i = 0; i < items.length; i++) {
  console.log("for:", i, items[i]);
}

for (const x of items) {
  console.log("for...of:", x);
}

items.forEach((x, i) => console.log("forEach:", i, x));

Common Mistakes

  1. Reading a missing index, getting `undefined`, then calling a method on it β†’ TypeError.
  2. Forgetting that `splice` mutates the array and accidentally running it twice.
  3. Comparing arrays with `===` (that's reference equality).
  4. Using `delete arr[1]` and creating a hole β€” use `splice` instead.
  5. Copying an object/array shallowly without realizing nested values are shared.

FAQ

Q1. Are arrays objects?

Yes. `typeof []` returns `"object"` β€” use `Array.isArray()` for a reliable check.

Q2. How do I check for an empty array?

`arr.length === 0` is the safe choice.

Q3. How do I copy an array?

`arr.slice()`, `[...arr]`, `Array.from(arr)` β€” all shallow copies.

Practice

  • `homework_01.js` β€” Find the min and max of an integer array.
  • `homework_02.js` β€” Return a new array with all occurrences of a target value removed.

homework/README.md

## homework_01.js β€” Write `minMax(arr)` that returns the min and max of an integer array.

## homework_02.js β€” Write `removeAll(arr, target)` that returns a **new** array with every occurrence of `target` removed (don't mutate the original).

homework/answer/homework_01.js

javascript
/**
 * Homework 1: min/max
 */
"use strict";

/**
 * @param {number[]} arr
 * @returns {{min:number,max:number}}
 */
function minMax(arr) {
  let min = arr[0];
  let max = arr[0];
  for (const x of arr) {
    if (x < min) min = x;
    if (x > max) max = x;
  }
  return { min, max };
}

console.log(minMax([3, 1, 4, 1, 5, 9, 2, 6])); // { min: 1, max: 9 }

homework/answer/homework_02.js

javascript
/**
 * Homework 2: remove all (without mutation)
 */
"use strict";

/**
 * @template T
 * @param {T[]} arr
 * @param {T} target
 * @returns {T[]}
 */
function removeAll(arr, target) {
  const result = [];
  for (const x of arr) {
    if (x !== target) result.push(x);
  }
  return result;
}

const original = [1, 2, 3, 2, 4, 2];
console.log(removeAll(original, 2)); // [1, 3, 4]
console.log("original =", original);

Next Lecture

[08_Strings](../08_λ¬Έμžμ—΄/) β€” Working with text.

Example code / lecture materials

All lecture materials and example code are openly available on GitHub.

View on GitHub β†—