JavaScript Objects & Arrays: Complete Tutorial
Learn how JavaScript objects and arrays work together. Covers creating, accessing, and modifying both data structures, destructuring, iteration, combining objects with arrays, and common real-world patterns with code examples.
Objects and arrays are the two core data structures in JavaScript. Arrays store ordered lists of values accessed by index. Objects store named properties accessed by key. Most real-world JavaScript code combines both: arrays of objects, objects containing arrays, and nested combinations of both. Understanding how they work individually and together is the foundation for handling any data in JavaScript.
This tutorial covers both data structures side by side, showing how to create, read, update, and delete data, plus the patterns you will use every day when working with APIs, databases, and user interfaces.
Arrays: Ordered Collections
An array holds an ordered list of values. Each value has a numeric index starting from zero.
// Creating arrays
const fruits = ["apple", "banana", "cherry"];
const numbers = [10, 20, 30, 40, 50];
const mixed = ["hello", 42, true, null, [1, 2]];
// Accessing elements
console.log(fruits[0]); // "apple"
console.log(fruits[2]); // "cherry"
// Array length
console.log(fruits.length); // 3Modifying Arrays
const tasks = ["design", "develop", "test"];
// Add to the end
tasks.push("deploy");
// ["design", "develop", "test", "deploy"]
// Remove from the end
const last = tasks.pop(); // "deploy"
// Add to the beginning
tasks.unshift("plan");
// ["plan", "design", "develop", "test"]
// Remove from the beginning
const first = tasks.shift(); // "plan"
// Replace an element by index
tasks[1] = "code";
// ["design", "code", "test"]For a deep dive into add/remove methods, see push and pop and shift and unshift.
Array Transformation Methods
| Method | What It Does | Returns |
|---|---|---|
| map() | Transforms every element | New array (same length) |
| filter() | Keeps elements passing a test | New array (subset) |
| reduce() | Accumulates into one value | Single value |
| find() | First element matching condition | Single element or undefined |
| some() | Tests if any element passes | Boolean |
| every() | Tests if all elements pass | Boolean |
| sort() | Sorts elements in place | Mutated original |
| flat() | Flattens nested arrays | New flattened array |
Objects: Named Properties
An object stores data as key-value pairs. Keys are strings (or Symbols), and values can be any type.
const user = {
name: "Alice",
age: 28,
email: "alice@example.com",
isActive: true
};
// Dot notation (preferred for known keys)
console.log(user.name); // "Alice"
// Bracket notation (required for dynamic keys)
const field = "email";
console.log(user[field]); // "alice@example.com"Modifying Objects
const product = {
name: "Laptop",
price: 999,
inStock: true
};
// Update a property
product.price = 899;
// Add a new property
product.brand = "TechCorp";
// Delete a property
delete product.inStock;
console.log(product);
// { name: "Laptop", price: 899, brand: "TechCorp" }Object Methods
Objects can contain functions as properties (called methods):
const counter = {
count: 0,
increment() {
this.count++;
return this.count;
},
decrement() {
this.count--;
return this.count;
},
reset() {
this.count = 0;
return this.count;
}
};
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
console.log(counter.decrement()); // 1
console.log(counter.reset()); // 0Combining Objects and Arrays
The most common real-world pattern is an array of objects. API responses, database results, and UI component lists all follow this pattern.
const employees = [
{ id: 1, name: "Alice", department: "Engineering", salary: 95000 },
{ id: 2, name: "Bob", department: "Marketing", salary: 72000 },
{ id: 3, name: "Charlie", department: "Engineering", salary: 105000 },
{ id: 4, name: "Diana", department: "Design", salary: 88000 },
{ id: 5, name: "Eve", department: "Marketing", salary: 68000 }
];
// Find a specific employee
const charlie = employees.find((emp) => emp.name === "Charlie");
console.log(charlie.salary); // 105000
// Get all engineers
const engineers = employees.filter((emp) => emp.department === "Engineering");
console.log(engineers.length); // 2
// Get names only
const names = employees.map((emp) => emp.name);
console.log(names); // ["Alice", "Bob", "Charlie", "Diana", "Eve"]
// Calculate total salary
const totalSalary = employees.reduce((sum, emp) => sum + emp.salary, 0);
console.log(totalSalary); // 428000
// Average salary
console.log(totalSalary / employees.length); // 85600Objects Containing Arrays
const course = {
title: "JavaScript Fundamentals",
instructor: "RuneHub Team",
duration: "8 weeks",
modules: [
{ week: 1, topic: "Variables & Data Types", lessons: 5 },
{ week: 2, topic: "Operators & Conditionals", lessons: 4 },
{ week: 3, topic: "Loops & Iteration", lessons: 6 },
{ week: 4, topic: "Functions", lessons: 7 }
],
tags: ["JavaScript", "Beginner", "Web Development"]
};
// Access nested data
console.log(course.modules[0].topic); // "Variables & Data Types"
// Total lessons across all modules
const totalLessons = course.modules.reduce((sum, mod) => sum + mod.lessons, 0);
console.log(`Total lessons: ${totalLessons}`); // Total lessons: 22Destructuring
Array destructuring and object destructuring let you extract values into named variables with clean syntax.
Array Destructuring
const coordinates = [40.7128, -74.0060, "New York"];
const [lat, lng, city] = coordinates;
console.log(lat); // 40.7128
console.log(lng); // -74.0060
console.log(city); // "New York"
// Skip elements
const [first, , third] = [10, 20, 30];
console.log(first); // 10
console.log(third); // 30Object Destructuring
const user = {
name: "Alice",
age: 28,
role: "developer",
skills: ["JavaScript", "Python"]
};
const { name, age, role } = user;
console.log(name); // "Alice"
console.log(role); // "developer"
// Rename while destructuring
const { name: userName, age: userAge } = user;
console.log(userName); // "Alice"
// Default values
const { country = "Unknown" } = user;
console.log(country); // "Unknown"Destructuring in Function Parameters
function displayEmployee({ name, department, salary }) {
console.log(`${name} works in ${department} and earns $${salary}`);
}
const emp = { id: 1, name: "Alice", department: "Engineering", salary: 95000 };
displayEmployee(emp);
// "Alice works in Engineering and earns $95000"Iterating Over Objects and Arrays
Arrays: for...of
const skills = ["JavaScript", "React", "Node.js"];
for (const skill of skills) {
console.log(`Skill: ${skill}`);
}Objects: for...in
const config = {
theme: "dark",
language: "en",
fontSize: 16
};
for (const key in config) {
console.log(`${key}: ${config[key]}`);
}
// theme: dark
// language: en
// fontSize: 16Object.keys, Object.values, Object.entries
const scores = { math: 95, science: 88, english: 92 };
console.log(Object.keys(scores)); // ["math", "science", "english"]
console.log(Object.values(scores)); // [95, 88, 92]
console.log(Object.entries(scores)); // [["math", 95], ["science", 88], ["english", 92]]
// Use entries with destructuring
for (const [subject, score] of Object.entries(scores)) {
console.log(`${subject}: ${score}`);
}Real-World Pattern: Grouping Data
const orders = [
{ id: 1, product: "Laptop", category: "Electronics", price: 999 },
{ id: 2, product: "Shirt", category: "Clothing", price: 29 },
{ id: 3, product: "Phone", category: "Electronics", price: 699 },
{ id: 4, product: "Pants", category: "Clothing", price: 49 },
{ id: 5, product: "Tablet", category: "Electronics", price: 449 }
];
// Group orders by category
const grouped = orders.reduce((groups, order) => {
const key = order.category;
if (!groups[key]) {
groups[key] = [];
}
groups[key].push(order);
return groups;
}, {});
console.log(grouped.Electronics.length); // 3
console.log(grouped.Clothing.length); // 2
// Sum by category
const categoryTotals = Object.entries(grouped).map(([category, items]) => ({
category,
total: items.reduce((sum, item) => sum + item.price, 0),
count: items.length
}));
console.log(categoryTotals);
// [
// { category: "Electronics", total: 2147, count: 3 },
// { category: "Clothing", total: 78, count: 2 }
// ]Common Mistakes
Confusing Array Index and Object Key
const arr = ["a", "b", "c"];
const obj = { 0: "a", 1: "b", 2: "c" };
// Arrays use numeric indices
console.log(arr[0]); // "a"
console.log(arr.length); // 3
// Objects have no .length by default
console.log(obj[0]); // "a"
console.log(obj.length); // undefinedCopying Arrays and Objects (Reference vs. Value)
// Bug: both variables point to the same array
const original = [1, 2, 3];
const copy = original;
copy.push(4);
console.log(original); // [1, 2, 3, 4] -- original was mutated!
// Fix: create a shallow copy
const safeCopy = [...original];
safeCopy.push(5);
console.log(original); // [1, 2, 3, 4] -- unaffected
// Same issue with objects
const user = { name: "Alice" };
const clone = { ...user };
clone.name = "Bob";
console.log(user.name); // "Alice" -- unaffected| Operation | Array | Object |
|---|---|---|
| Shallow copy | [...arr] or arr.slice() | { ...obj } or Object.assign({}, obj) |
| Deep copy | structuredClone(arr) | structuredClone(obj) |
| Check if empty | arr.length === 0 | Object.keys(obj).length === 0 |
| Iterate values | for...of | Object.values() or for...in |
| Convert to other | Object.entries(obj) | Object.fromEntries(arr) |
Rune AI
Key Insights
- Arrays are for ordered data, objects are for named data: choose based on whether position or property name matters more.
- Arrays of objects are the dominant pattern: API responses, database rows, and UI lists all follow this structure.
- Destructuring simplifies extraction: use
const { name } = objandconst [first, second] = arrfor concise, readable code. - Copying requires attention: spread (
...) creates shallow copies; usestructuredClone()when nested data must be fully independent. - Object.keys, values, and entries bridge the gap: they convert objects into arrays so you can use map, filter, and reduce on object data.
Frequently Asked Questions
When should I use an array versus an object?
How do I check if a value exists in an array?
What is the difference between a shallow copy and a deep copy?
How do I merge two objects in JavaScript?
Can arrays contain objects and other arrays?
Conclusion
Objects and arrays are inseparable in JavaScript. Arrays give you ordered, index-based access with powerful transformation methods like map, filter, and reduce. Objects give you named, key-based access ideal for structured data. Most real-world code combines both: arrays of objects for collections, objects containing arrays for grouped data, and destructuring for clean extraction of nested values. Mastering how these two structures interact is the single most practical skill for working with JavaScript data.
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.