Skip to content
elephantoo

Arrays & objects: the basics

Lesson 9 of 34 14 min read

Create, read, update and loop over arrays and objects — JavaScript’s two workhorse structures.


Almost all real data is a collection: a list of products, a user profile, a table of scores. JavaScript's two workhorse structures are arrays (ordered lists) and objects (named properties). This lesson covers the basics of both; the following lessons go deeper.

Arrays: ordered lists#

JavaScript
const langs = ["JavaScript", "Python", "Java"];

console.log(langs[0]);     // "JavaScript" – indexes start at 0
console.log(langs.length); // 3
console.log(langs.at(-1)); // "Java" – negative index counts from the end
console.log(langs[10]);    // undefined – no error for missing indexes

Arrays can hold any mix of types, including other arrays and objects — but in practice, keep each array to one kind of thing.

JavaScript
const matrix = [
  [1, 2],
  [3, 4],
];
console.log(matrix[1][0]); // 3

Adding and removing items

JavaScript
const queue = ["Ada", "Grace"];

queue.push("Alan");       // add to the end → returns new length 3
queue.unshift("Linus");   // add to the start
console.log(queue);       // [ 'Linus', 'Ada', 'Grace', 'Alan' ]

const last = queue.pop();    // remove from the end → "Alan"
const first = queue.shift(); // remove from the start → "Linus"
console.log(first, last, queue); // Linus Alan [ 'Ada', 'Grace' ]

queue[1] = "Margaret";    // replace by index
console.log(queue);       // [ 'Ada', 'Margaret' ]

push, pop, shift, unshift and index assignment mutate (change) the array in place.

splice and slice

JavaScript
const letters = ["a", "b", "c", "d", "e"];

// slice(start, end) copies a portion – original unchanged
console.log(letters.slice(1, 3)); // [ 'b', 'c' ]

// splice(start, deleteCount, ...items) changes the original
const removed = letters.splice(1, 2, "X");
console.log(removed); // [ 'b', 'c' ]
console.log(letters); // [ 'a', 'X', 'd', 'e' ]

Mnemonic: splice has a "p" for "permanent change". Modern JavaScript also has toSpliced, a non-mutating version — covered in Array methods.

Searching

JavaScript
const tags = ["html", "css", "js"];
console.log(tags.includes("css")); // true
console.log(tags.indexOf("js"));   // 2
console.log(tags.indexOf("php"));  // -1
console.log(Array.isArray(tags));  // true

Looping over an array

JavaScript
const scores = [72, 95, 88];

for (const score of scores) {
  console.log(score);
}

scores.forEach((score, index) => {
  console.log(`#${index + 1}: ${score}`);
});
Output
72
95
88
#1: 72
#2: 95
#3: 88

Objects: named properties#

An object groups related values under keys (property names):

JavaScript
const user = {
  name: "Ada",
  born: 1815,
  languages: ["Analytical Engine"],
  "favourite colour": "purple", // keys with spaces need quotes
};

console.log(user.name);                // "Ada" – dot notation
console.log(user["born"]);             // 1815 – bracket notation
console.log(user["favourite colour"]); // "purple"
console.log(user.email);               // undefined – missing property

Dot vs bracket notation

Use dot notation normally. Use brackets when the key is in a variable or isn't a valid identifier:

JavaScript
const product = { id: 7, price: 499, stock: 12 };
const field = "price";
console.log(product[field]); // 499
console.log(product.field);  // undefined – looks for a key literally called "field"

Adding, changing and removing properties

JavaScript
const settings = { theme: "light" };
settings.theme = "dark";      // change
settings.fontSize = 16;       // add
delete settings.fontSize;     // remove
console.log(settings);        // { theme: 'dark' }

console.log("theme" in settings);      // true
console.log(Object.hasOwn(settings, "language")); // false

Methods: functions inside objects

JavaScript
const course = {
  title: "JavaScript",
  lessons: 34,
  describe() {
    return `${this.title} has ${this.lessons} lessons`;
  },
};

console.log(course.describe()); // JavaScript has 34 lessons

Inside a method, this refers to the object the method was called on. There's a full lesson on this later.

Looping over an object

JavaScript
const stock = { apples: 12, bananas: 0, cherries: 40 };

console.log(Object.keys(stock));   // [ 'apples', 'bananas', 'cherries' ]
console.log(Object.values(stock)); // [ 12, 0, 40 ]

for (const [fruit, count] of Object.entries(stock)) {
  console.log(`${fruit}: ${count > 0 ? count : "sold out"}`);
}
Output
[ 'apples', 'bananas', 'cherries' ]
[ 12, 0, 40 ]
apples: 12
bananas: sold out
cherries: 40

Arrays of objects: real-world data#

Most data from APIs looks like this:

JavaScript
const courses = [
  { title: "Java", lessons: 30, done: 30 },
  { title: "React", lessons: 29, done: 6 },
  { title: "Linux", lessons: 25, done: 0 },
];

for (const c of courses) {
  const percent = Math.round((c.done / c.lessons) * 100);
  console.log(`${c.title.padEnd(6)} ${percent}%`);
}
Output
Java   100%
React  21%
Linux  0%

References: why copies surprise people#

Arrays and objects are stored by reference. Assigning one to another variable doesn't copy it — both names point to the same data:

JavaScript
const original = [1, 2, 3];
const alias = original;
alias.push(4);
console.log(original); // [ 1, 2, 3, 4 ] – same array!

const copy = [...original]; // a real (shallow) copy
copy.push(5);
console.log(original.length, copy.length); // 4 5

console.log([1, 2] === [1, 2]); // false – two different arrays

=== on objects compares identity, not contents. Copying and comparing are covered properly in Objects in depth and Destructuring & spread.

Arrays or objects?#

Use an array when…Use an object when…
Order mattersYou look things up by name
Items are the same kind of thingValues describe one thing
You'll loop, sort, filterYou'll access user.email, user.name

For lookups by arbitrary keys (like ids) or when keys aren't strings, a Map is often better — see Map, Set, WeakMap & WeakSet.

Common mistakes#

  • Reading arr[arr.length] — the last element is at length - 1.
  • Using obj.key when key is a variable.
  • Thinking const arr = [] can't change — it can be mutated, just not reassigned.
  • Expecting === to compare the contents of two arrays or objects.

What's next#

You can store and access collections. Next, transform them like a pro with array methods: map, filter, reduce, find, sort and more.

Check your understanding

Quick quiz

0/3 answered
  1. 1.Given const langs = ["JS", "Python", "Java"];, what is langs[langs.length - 1]?

  2. 2.Which is the right way to read a property whose name is stored in a variable key?

  3. 3.Which array method adds an item to the **start** of an array?

Finished reading?

Mark this lesson complete to track your progress.