Arrays & Objects

Published by Brayan K

Master JavaScript's most important data structures for organizing, storing, and manipulating data.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Use a list of records when each item has named fields

An array answers “which item is at this position?” An object answers “what is this record’s named value?” Combining them gives a list of records. Keep the shape consistent: in this example every book has an id, a title and an available Boolean. The array position is temporary; the id is the application’s stable identifier.

const books = [
  { id: "b7", title: "Loops", available: true },
  { id: "b2", title: "Functions", available: false }
];
const chosen = books.find(book => book.id === "b7");
if (chosen !== undefined) chosen.available = false;
console.log(books.length);
console.log(books[0].title, books[0].available);
console.log(books[1].title, books[1].available);

// ✅ Expected output:
// 2
// Loops false
// Functions false

find returns a matching value, not a copy. Updating chosen therefore updates the same object held in books. The guard handles the missing-record case. Transforming a whole array belongs to map, filter & reduce; this lesson focuses on selecting, maintaining and inspecting a collection’s shape.

const book = { id: "b7", title: "Loops" };
console.log(Array.isArray(book));
book.push({ id: "b2", title: "Functions" });

// ✅ Expected output:
// false

// ✅ Expected error:
// TypeError: book.push is not a function

An index is a position, not an identifier

The first array element uses index zero. Reading beyond the length returns undefined. Negative bracket keys do not count from the end: at(-1) is the array method for that request. Use a record’s field when your input is an id; treating the id as an index silently asks a different question.

const books = [
  { id: 20, title: "Loops" },
  { id: 10, title: "Functions" }
];
console.log(books[0].id);
console.log(books[20]);
console.log(books[-1]);
console.log(books.at(-1).title);
console.log(books.find(book => book.id === 20).title);

// ✅ Expected output:
// 20
// undefined
// undefined
// Functions
// Loops

A failed find returns undefined. Accessing a property immediately after it turns an ordinary “not found” result into an error. Decide whether absence should return a status, show an empty state or throw a deliberate application error.

const books = [{ id: "b7", title: "Loops" }];
const book = books.find(item => item.id === "missing");
console.log(book === undefined);
console.log(book.title);

// ✅ Expected output:
// true

// ✅ Expected error:
// TypeError: Cannot read properties of undefined (reading 'title')
function titleFor(books, id) {
  const book = books.find(item => item.id === id);
  if (book === undefined) return null;
  return book.title;
}
const books = [{ id: "b7", title: "Loops" }];
console.log(titleFor(books, "b7"));
console.log(titleFor(books, "missing"));
console.log(titleFor([], "b7"));

// ✅ Expected output:
// Loops
// null
// null

Array methods can change the array and return something else

push and unshift add items at the end or start and return the new length. pop and shift remove an item and return that item; an empty array returns undefined. Do not replace your array variable with one of those return values when you meant to keep working with the list.

const queue = ["A"];
const length = queue.push("B");
console.log(length, JSON.stringify(queue));
console.log(queue.shift(), JSON.stringify(queue));
console.log(queue.pop(), queue.length);
console.log(queue.pop(), queue.length);
console.log(queue.unshift("C"), JSON.stringify(queue));

// ✅ Expected output:
// 2 ["A","B"]
// A ["B"]
// B 0
// undefined 0
// 1 ["C"]
let queue = ["A"];
queue = queue.push("B");
console.log(queue, typeof queue);
queue.push("C");

// ✅ Expected output:
// 2 number

// ✅ Expected error:
// TypeError: queue.push is not a function

slice selects a range into a new array without removing it from the original. splice changes the original and returns the removed elements. Its second argument is a count, not an ending index. A negative starting index counts back from the end, which makes an unchecked search result especially dangerous.

const values = ["A", "B", "C", "D"];
console.log(JSON.stringify(values.slice(1, 3)));
console.log(JSON.stringify(values));
const removed = values.splice(1, 2, "X");
console.log(JSON.stringify(removed));
console.log(JSON.stringify(values));

// ✅ Expected output:
// ["B","C"]
// ["A","B","C","D"]
// ["B","C"]
// ["A","X","D"]
const books = [{ id: "b7" }, { id: "b2" }];
const index = books.findIndex(book => book.id === "missing");
console.log(index);
books.splice(index, 1);
console.log(JSON.stringify(books));

// ✅ Expected output:
// -1
// [{"id":"b7"}]

Check index !== -1 before splicing. Avoid if (index): zero is a valid first position, while -1 is truthy. The independent brief applies the explicit missing-index check.

Removing an array property does not close the gap

delete removes a property. For an array index it leaves a hole and does not shorten the array. Assigning far beyond the end also creates gaps. A hole and a present element whose value is undefined can both read as undefined, so inspect membership when the distinction matters. Use splice when you mean to remove a list position and shift later items down.

const values = ["A", undefined, "C"];
delete values[0];
console.log(values.length);
console.log(values[0], values[1]);
console.log(0 in values, 1 in values);
console.log(JSON.stringify(Object.keys(values)));
values.splice(0, 1);
console.log(values.length, 0 in values);

// ✅ Expected output:
// 3
// undefined undefined
// false true
// ["1","2"]
// 2 true

For a normal dense list, length is the number of positions you expect to visit. With holes, it is not the count of stored elements. Callback behaviour on sparse arrays is covered in map, filter & reduce. JSON formatting can also hide this distinction, so the example prints membership separately.

Property names are data when you use brackets

Dot notation selects the literal property name you write. Bracket notation evaluates an expression to choose a key, making it suitable for a selected field or a name containing spaces. Do not use a falsey check to decide whether a property exists: zero, false and an empty string can be valid values.

const book = { title: "Loops", copies: 0, "shelf code": "A-2" };
const field = "title";
console.log(book.field);
console.log(book[field]);
console.log(book["shelf code"]);
console.log(Object.hasOwn(book, "copies"), Boolean(book.copies));
console.log(Object.hasOwn(book, "missing"));

// ✅ Expected output:
// undefined
// Loops
// A-2
// true false
// false

Object.hasOwn asks whether this object itself has the property, including a property whose value is undefined. The in operator can also find inherited properties. Full enumeration and property-descriptor rules belong to Object Methods (keys, entries, assign, freeze).

const book = { id: "b7", title: "Loops", copies: 0 };
console.log(JSON.stringify(Object.keys(book)));
console.log(JSON.stringify(Object.values(book)));
for (const [field, value] of Object.entries(book)) {
  console.log(field + ": " + value);
}

// ✅ Expected output:
// ["id","title","copies"]
// ["b7","Loops",0]
// id: b7
// title: Loops
// copies: 0

These three methods visit own enumerable string-keyed properties; they are not a list of every possible property, such as symbol keys or inherited fields. Here the fixed record uses ordinary named fields. Grouping and indexing larger record collections belongs to Advanced Array & Object Transformations.

Equality and copying depend on which object you hold

Two separate object literals remain separate objects even if their fields look equal. includes uses identity for objects, so a newly written record literal will not find an existing record. Search by the field that defines identity for your application instead.

const original = { id: "b7" };
const books = [original];
console.log(books.includes(original));
console.log(books.includes({ id: "b7" }));
console.log(books.some(book => book.id === "b7"));

// ✅ Expected output:
// true
// false
// true

Copying an array with slice separates the outer list but keeps references to its records. A record update can therefore affect both arrays. Spread & Rest Operators owns copying the changed record and each changed level; choose that deliberately when you need an unchanged input.

const original = [{ id: "b7", copies: 2 }];
const copy = original.slice();
copy.push({ id: "b2", copies: 1 });
copy[0].copies = 0;
console.log(original.length, copy.length);
console.log(original[0].copies, copy[0].copies);
console.log(original === copy, original[0] === copy[0]);

// ✅ Expected output:
// 1 2
// 0 0
// false true

Guided exercise: remove the first matching ID safely

Fill the three blanks to find an ID, reject the missing-index sentinel, and remove exactly one position. This exercise intentionally mutates the supplied list. Notice that the matched item is at index zero, so a truthiness check would be wrong.

const books = [{ id: "b7" }, { id: "b2" }];
const index = books.___(book => book.id === "b7"); // 👉 replace ___ with findIndex
if (index !== ___) { // 👉 replace ___ with -1
  books.splice(index, ___); // 👉 replace ___ with 1
}
console.log(JSON.stringify(books));

// ✅ Expected output:
// [{"id":"b2"}]

Independent brief: return a removal result without changing the input list

Write removeBook(books, id) for a dense array of records with unique string IDs. Return an object with removed (the matching record or null) and remaining (a new array). Remove at most one record, preserve the order of the others, and keep the original array and records unchanged.

This is a shallow list operation: remaining may share record objects with books, and removed is the original matching record. It is not a deep clone. Check the first and last positions, a missing ID, an empty array, and the original input after all calls.

function removeBook(books, id) {
  const remaining = books.slice();
  const index = remaining.findIndex(book => book.id === id);
  if (index === -1) return { removed: null, remaining };
  const [removed] = remaining.splice(index, 1);
  return { removed, remaining };
}
const books = [
  { id: "b7", title: "Loops" },
  { id: "b2", title: "Functions" },
  { id: "b9", title: "DOM" }
];
const before = JSON.stringify(books);
for (const id of ["b7", "b2", "b9", "missing"]) {
  const result = removeBook(books, id);
  console.log(id, result.removed === null ? null : result.removed.id,
    result.remaining.map(book => book.id).join(","));
}
console.log(JSON.stringify(removeBook([], "b7")));
console.log(JSON.stringify(books) === before);
const result = removeBook(books, "b7");
console.log(result.remaining !== books);
console.log(result.removed === books[0], result.remaining[0] === books[1]);

// ✅ Expected output:
// b7 b7 b2,b9
// b2 b2 b7,b9
// b9 b9 b7,b2
// missing null b7,b2,b9
// {"removed":null,"remaining":[]}
// true
// true
// true true

Practice quiz

What does this complete program print? const books = [{ id: 20 }, { id: 10 }]; console.log(books[0].id, books.at(-1).id); console.log(books[20]);

  • 20 10 undefined
  • 20 10 20
  • 10 20 undefined
  • 20 20 undefined

Answer: 20 10 undefined. The array position is independent of each record’s id. at(-1) selects the final element.

What does this complete program print? const values = ["A"]; const result = values.push("B"); console.log(result, JSON.stringify(values));

  • ["A","B"] ["A"]
  • 2 ["A","B"]
  • 1 ["A","B"]
  • 2 ["B"]

Answer: 2 ["A","B"]. push changes the array and returns its new length.

What does this complete program print? const values = ["A", "B"]; const index = values.indexOf("missing"); values.splice(index, 1); console.log(JSON.stringify(values));

  • ["A","B"]
  • ["B"]
  • ["A"]
  • []

Answer: ["A"]. indexOf returns -1, and splice treats -1 as the last position. Check the sentinel before changing the array.

What does this complete program print? const values = ["A", undefined]; delete values[0]; console.log(values.length, 0 in values, 1 in values);

  • 1 false true
  • 2 true true
  • 1 false false
  • 2 false true

Answer: 2 false true. delete leaves a hole and keeps length. The second slot still exists even though its value is undefined.

What does this complete program print? const record = { name: "Ada", count: 0 }; const field = "name"; console.log(record[field], record.field); console.log(Object.hasOwn(record, "count"));

  • Ada undefined true
  • Ada name true
  • Ada undefined false
  • undefined undefined true

Answer: Ada undefined true. Brackets evaluate field; dot notation looks for a literal field property. Zero is still a present count value.

What does this complete program print? const first = { id: "a", count: 2 }; const original = [first]; const copy = original.slice(); copy[0].count = 0; console.log(original[0].count, original === copy);

  • 2 false
  • 0 false
  • 0 true
  • 2 true

Answer: 0 false. slice copies the array, while both arrays still hold the same record reference.

What does this complete program print? const item = { id: "a" }; const values = [item]; console.log(values.includes({ id: "a" }), values.includes(item));

  • true true
  • false false
  • false true
  • true false

Answer: false true. Object values are matched by identity, not by comparing their fields.

What does this complete program print? const values = ["A", "B", "C"]; const removed = values.splice(1, 1); console.log(JSON.stringify(removed)); console.log(JSON.stringify(values));

  • ["B","C"] ["A"]
  • ["A"] ["B","C"]
  • ["B"] ["A","B","C"]
  • ["B"] ["A","C"]

Answer: ["B"] ["A","C"]. The second argument removes one item, and splice returns that removed item in an array.

Continue this course

Related lessons