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.

JavaScriptbeginner
17 min read

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.

javascriptjavascript
// 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); // 3

Modifying Arrays

javascriptjavascript
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

MethodWhat It DoesReturns
map()Transforms every elementNew array (same length)
filter()Keeps elements passing a testNew array (subset)
reduce()Accumulates into one valueSingle value
find()First element matching conditionSingle element or undefined
some()Tests if any element passesBoolean
every()Tests if all elements passBoolean
sort()Sorts elements in placeMutated original
flat()Flattens nested arraysNew flattened array

Objects: Named Properties

An object stores data as key-value pairs. Keys are strings (or Symbols), and values can be any type.

javascriptjavascript
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

javascriptjavascript
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):

javascriptjavascript
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());     // 0

Combining 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.

javascriptjavascript
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); // 85600

Objects Containing Arrays

javascriptjavascript
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: 22

Destructuring

Array destructuring and object destructuring let you extract values into named variables with clean syntax.

Array Destructuring

javascriptjavascript
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); // 30

Object Destructuring

javascriptjavascript
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

javascriptjavascript
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

javascriptjavascript
const skills = ["JavaScript", "React", "Node.js"];
 
for (const skill of skills) {
  console.log(`Skill: ${skill}`);
}

Objects: for...in

javascriptjavascript
const config = {
  theme: "dark",
  language: "en",
  fontSize: 16
};
 
for (const key in config) {
  console.log(`${key}: ${config[key]}`);
}
// theme: dark
// language: en
// fontSize: 16

Object.keys, Object.values, Object.entries

javascriptjavascript
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

javascriptjavascript
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

javascriptjavascript
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); // undefined

Copying Arrays and Objects (Reference vs. Value)

javascriptjavascript
// 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
OperationArrayObject
Shallow copy[...arr] or arr.slice(){ ...obj } or Object.assign({}, obj)
Deep copystructuredClone(arr)structuredClone(obj)
Check if emptyarr.length === 0Object.keys(obj).length === 0
Iterate valuesfor...ofObject.values() or for...in
Convert to otherObject.entries(obj)Object.fromEntries(arr)
Rune AI

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 } = obj and const [first, second] = arr for concise, readable code.
  • Copying requires attention: spread (...) creates shallow copies; use structuredClone() 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.
RunePowered by Rune AI

Frequently Asked Questions

When should I use an array versus an object?

Use arrays for ordered collections where position matters (lists of items, queue of tasks, series of values). Use objects for named data where you access values by meaningful keys (user profiles, configuration settings, entity records). Use arrays of objects when you need a collection of structured items, which is the most common pattern in JavaScript applications.

How do I check if a value exists in an array?

Use `includes()` for simple values: `[1, 2, 3].includes(2)` returns `true`. Use `find()` to locate an object by property: `users.find(u => u.name === "Alice")`. Use `some()` to check if any element meets a condition: `numbers.some(n => n > 100)`. Each method serves a different use case depending on what you are looking for.

What is the difference between a shallow copy and a deep copy?

shallow copy creates a new array or object at the top level, but nested arrays and objects still point to the same references. Changing a nested property in the copy affects the original. A deep copy recursively duplicates every level, so the copy is completely independent. Use `structuredClone()` for deep copies and the spread operator (`...`) for shallow copies.

How do I merge two objects in JavaScript?

Use the spread operator: `const merged = { ...obj1, ...obj2 }`. If both objects have the same key, the second object's value wins. For more control, use `Object.assign(target, source1, source2)`. Both create shallow merges; nested objects are still shared by reference.

Can arrays contain objects and other arrays?

Yes, JavaScript arrays can hold any data type: strings, numbers, booleans, objects, other arrays, functions, and even mixed types. Arrays of objects (like `[{ name: "Alice" }, { name: "Bob" }]`) are the most common pattern for representing collections of structured data in web applications, API responses, and database results.

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.