JavaScript + Node.js track

Lesson 07 · Part 2: Objects & Arrays

Array Fundamentals

Indexes, `push`/`pop`/`shift`/`unshift` and iteration

Part 2: Objects & Arrays2 min readFree lesson

Level: Intermediate | Player: 06_Object

Learning Objectives

  • You can create an array and use Access/Modify as the index.
  • Understand the meaning and operation of length.
  • Elements can be Add/Delete as push, pop, shift, and unshift.
  • Know the difference between splice and slice (whether the original has been changed or not).
  • Iterate through the array with for...of.

1. Array creation and index

An array is an ordered collection of values, accessed by index starting from 0.

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

length is the largest index + 1. If you shorten it like fruits.length = 1, the rear elements will be cut off.

2. Adding and removing end/front

push/pop operates at the end, and unshift/shift operates at the front. Forward operations are slower because they move all elements.

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 and slice

splice(start, deleteCount, ...items) changes the original, and slice(start, end) returns a new array (without end).

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] As original

4. Traversal (for...of)

If you don't need an index, for...of is the most concise. If you also need an index, use entries().

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

Core example

file Contents covered
01_index.js Index access, length operation
02_push_pop.js Add/Delete method
03_splice.js splice vs slice
04_iteration.js for, for...of, forEach

⚠️ Common Mistakes

  1. Reading an index that does not exist and calling a method on undefined causes a TypeError.
  2. Apply it twice, forgetting that splice changes the original.
  3. Try to compare the array with === (reference comparison).
  4. Create an empty slot using delete arr[1] — use splice.
  5. When copying an object or array, it is not recognized as a shallow copy.

❓ Frequently Asked Questions (FAQ)

Q1. Are arrays also objects? A. Yes. typeof [] is "object", and to determine it accurately, use Array.isArray().

Q2. What about checking for empty arrays? A. arr.length === 0 is safe.

Q3. How to copy an array? A. arr.slice(), [...arr], and Array.from(arr) all make shallow copies.

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

src/01_index.jsJavaScript
/**
 *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.jsJavaScript
/**
 *Add/Delete Method
 */
"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.jsJavaScript
/**
 * 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.jsJavaScript
/**
 *Array traversal method
 */
"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));

Assignment

homework_01.js

Write minMax(arr), which takes an array of integers and returns the maximum and minimum values.

homework_02.js

Write removeAll(arr, target) which takes an array and two values and returns a new array with all the values removed. (Do not change the original)

Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

homework_01.jsJavaScript
/**
 *Challenge 1: Maximum/Minimum
 */
"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_02.jsJavaScript
/**
 *Challenge 2: Remove values (preserve original)
 */
"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);

Learn this lesson with a mentor

Work through the JavaScript + Node.js track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now