Web Development

JavaScript Arrays and Objects: Store and Use Data

Flat illustration of a list and a labelled record side by side

A single variable holds a single value, and that is not enough for most real programs. A page that shows a list of articles, a form that collects several fields, or a shopping list all need to hold many values together, in a form that code can read and change. JavaScript gives two main tools for that job: arrays, which hold an ordered list of values, and objects, which hold values under names.

The difference between the two is the question each one answers. An array answers the question of what comes first, second and third, because its items sit in order and each one has a position. An object answers the question of what each value is called, because its values sit under keys, and code reads a value by its key. Choosing the right tool starts with asking which question your data needs to answer.

Arrays: an ordered list

An array is written with square brackets, and its items are separated by commas. The first item sits at position zero, the second at position one, and so on. That zero-based counting is the most common source of beginner errors with arrays, because the third item is at position two, not position three. The length property gives the number of items, so an array with three items has a length of three, and its last position is two.

The example below creates a list of colours, reads one item, and adds a new item at the end. The push method adds an item to the end of an array, and it is one of the most used array methods in everyday code. Reading an item uses square brackets with the position inside them, which is a different use of square brackets from creating the array, even though the symbols look the same.

const colours = ["red", "green", "blue"];
console.log(colours[0]);
colours.push("yellow");
console.log(colours.length);

The JavaScript basics guide covers variables and functions, which are the background for this guide. A loop is the usual way to work through every item in an array, because it runs the same code once per item without writing the code out for each position. The forEach method does the same job in a shorter form, by running a function once for each item. Either form works, and the choice between them is mostly a matter of what the surrounding code already uses.

const scores = [12, 18, 15];
scores.forEach(function (score) {
  console.log(score);
});

Objects: values under names

An object is written with curly braces, and its contents are pairs of a key and a value, separated by commas. A key is usually a short name, and the value can be a string, a number, a list, or another object. The example below describes a user with a name, a role and a list of skills. Each value is reached by its key, so the code that reads it says what it wants in plain words, rather than relying on a position.

const user = {
  name: "Sara",
  role: "editor",
  skills: ["HTML", "CSS"]
};

console.log(user.name);
console.log(user.skills[1]);

Dot notation reads a property when its name is known while writing the code, as in user.name. Bracket notation reads a property when its name is stored in a variable, as in user[key], or when the name contains a character that dot notation cannot handle. Both forms read the same property when the name matches, and the choice depends on whether the key is fixed or variable. Adding a new property is a matter of assigning a value to a key that does not exist yet, and changing a value is the same assignment to a key that already exists.

Objects are often combined with arrays in a single structure. An array of objects describes a list where each item has named fields, such as a list of articles where each article has a title and a link. Code can loop over the array and read the same keys from each object, which is a pattern that appears in almost every page that renders a list from data. The JavaScript DOM guide shows how data like this ends up on a page, and the JavaScript events guide shows how a click or an input can change it.

const articles = [
  { title: "HTML basics", readTime: 8 },
  { title: "CSS grid", readTime: 6 }
];

articles.forEach(function (article) {
  console.log(article.title);
});
StructureUse it whenHow you read a value
ArrayOrder matters and items are similarBy position, starting from zero
ObjectEach value needs a nameBy key, with dot or bracket notation
Array of objectsA list of named things is neededLoop the array, read keys from each object

Common mistakes

The most frequent array mistake is an off-by-one error, where code reads position three in an array that only has three items. Since positions start at zero, the last position is always one less than the length, and reading the position equal to the length gives undefined. Checking the length before reading, or looping with a method that handles positions for you, avoids most of these errors.

A second mistake is treating a copied array or object as an independent copy. Assigning an array to a second variable copies the reference, so both variables point to the same contents. Changing the contents through one variable then shows up through the other, which can look like a bug in unrelated code. When an independent copy is needed, create a new array or object and copy the contents into it, rather than assigning the original variable.

A third mistake is reading a property from a value that is undefined, which happens when a key is misspelled or when an array position is out of range. The error message for this case points at the line that tried to read the property, not at the misspelling itself, so the fix is to check the key or the position first. Logging the object or array before the failing line shows its actual shape, and the difference between the expected shape and the actual shape usually reveals the mistake.

Where these structures do not fit

Arrays and objects cover most beginner data, but they do not cover every case. A value that must stay unique, or a value that must be looked up by a key that is itself an object, needs a different structure, and those cases belong to a later guide. For the data in this guide, arrays and objects are the right tools, and reaching for a more specialised structure too early adds complexity without a clear gain.

Arrays and objects also do not store data between page loads on their own. When a page is reloaded, variables are created again from the code, and any changes made during the visit are lost unless the code saves them somewhere. Saving data to a server or to browser storage is a separate topic, and it should not be confused with holding data in a variable while a page is open. The distinction matters, because a program that works during a visit can still lose its data on reload if nothing saves it.

Worked example: a small book catalogue

A book catalogue shows why arrays and objects are usually used together. An array holds the list of books, and each book is an object with properties for its title, author and year. The array gives the order and the count, and the objects give each book its details. Separating the two roles keeps the code readable: the array answers "which books", and each object answers "what is this book".

const books = [
  { title: "Dune", author: "Frank Herbert", year: 1965 },
  { title: "Emma", author: "Jane Austen", year: 1815 },
];

const firstTitle = books[0].title;
console.log(firstTitle); // Dune

Access follows the structure. Books[0] gives the first book object, and adding .title reads that book title property. That chain reads from left to right as a path through the data, which is why consistent property names matter: a catalogue where one book uses author and another uses writer forces every reader of the code to check which name each book used.

Adding a book means pushing a new object onto the array, and the shape of the new object should match the existing ones. A book missing its year property will not break the code, but it will produce an undefined value wherever the year is displayed, which looks like a bug to a reader even though the code ran without an error. Keeping the shape consistent prevents that class of silent problem.

Map, filter and find: transform without loops

Array methods such as map, filter and find express common operations without writing a loop by hand. Map builds a new array by transforming each item, such as extracting the title of every book. Filter builds a new array holding only the items that pass a test, such as books published after a given year. Find returns the first item that passes a test, or undefined when nothing passes.

const titles = books.map(function (book) {
  return book.title;
});
const recent = books.filter(function (book) {
  return book.year > 1900;
});
const emma = books.find(function (book) {
  return book.title === "Emma";
});

These methods return new values rather than changing the original array, which keeps the original data intact for other uses. That immutability habit pays off when the same data feeds several parts of a page, because a transformation in one place cannot silently change the data another place depends on. When a transformation should change the original, that decision should be explicit, not a side effect of a method call.

Chaining methods reads naturally when each step is one idea. Filtering books by year and then mapping the result to titles is two steps, and writing them as a chain shows the pipeline in order. Chains longer than two or three steps become hard to follow, so a longer pipeline is better split into named intermediate values that explain each stage.

Objects as lookups: when keys beat lists

An array suits ordered data, and an object suits data looked up by name. A settings object, for example, holds values under keys such as theme and language, and reading settings.theme gives the value directly, without searching. A list of settings would need a search for the right entry every time, which is slower to write and slower to read. The rule of thumb is simple: order matters, use an array; lookup by name matters, use an object.

const settings = {
  theme: "dark",
  language: "en",
};

console.log(settings.theme); // dark
console.log(settings["language"]); // en

Dot notation and bracket notation both read a property, and the choice depends on the key. Dot notation suits keys known when the code is written, and it reads more cleanly. Bracket notation suits keys held in a variable, or keys that are not valid identifiers, such as keys containing spaces or hyphens. A lookup where the key comes from user input or from another data structure needs bracket notation, because dot notation cannot use a variable as a key.

Objects also serve as a simple dictionary for counting and grouping. Counting how many books each author wrote, for example, can be done with an object whose keys are author names and whose values are counts. That pattern appears often enough that it is worth recognising: when the result is a set of named totals, an object is usually the natural container.

Copying, nesting and common mistakes

Copying an array or an object with assignment copies the reference, not the contents, so two variables end up pointing at the same data. Changing the data through one variable changes what the other variable sees, which surprises beginners who expected an independent copy. The spread syntax makes a shallow copy, which copies the top level but still shares nested objects, so a nested change still affects the original. A truly independent copy of nested data needs a deeper copy, and the method for that depends on the data involved.

const original = [1, 2, 3];
const copy = [...original];
copy.push(4);
// original is still [1, 2, 3]

Nested access is the second common trouble spot. Reading books[0].title fails when the array is empty, because books[0] is undefined and undefined has no title property. Guarding the access, or checking the length first, prevents that error. The optional chaining operator offers a shorter guard for deeply nested data, returning undefined instead of throwing, though it should not be used to hide a genuine data problem that ought to be fixed at its source.

A third mistake is mixing up array and object syntax, such as using a numeric index on an object or a string key on an array. JavaScript often accepts the mistake without an error and returns undefined, which makes the bug hard to trace. Checking the shape of the data, by logging it before the failing line, usually reveals the mismatch at once.

Frequently asked questions

When should I use an array and when should I use an object?

Use an array when the order matters and the items are of a similar kind, such as a list of scores. Use an object when each value needs a name, such as a user with a name, an email address and a role. When a list of named things is needed, an array of objects covers both needs.

Why does changing one variable change another one too?

Arrays and objects are reference types, so assigning one to a second variable copies the reference, not the contents. Changing the contents through one variable then shows up through the other, because both point to the same array or object. Copying the contents into a new array or object avoids that shared change.

What is the difference between dot notation and bracket notation?

Dot notation reads a property whose name you know when you write the code, such as user.name. Bracket notation reads a property whose name is stored in a variable, such as user[key], or a name that is not a valid identifier. Both read the same property when the name matches.

When should I use an array and when an object?

Use an array when order matters or when you hold a list of similar items. Use an object when you look values up by name, such as settings or a record with named fields. Most real data uses both: an array of objects, where the array holds the order and each object holds the details.

Why did changing my copy also change the original?

Assignment copies the reference to the data, not the data itself, so both variables point at the same array or object. Spread syntax makes a shallow copy, which is independent at the top level but still shares nested objects.

Sources