JavaScript Fundamentals: Objects and Arrays
Objects and arrays are the workhorses of JavaScript. Whether you’re storing user data, handling form submissions, or processing API responses, you’ll reach for these data structures constantly. This guide teaches you how to create, manipulate, and choose between objects and arrays.
What Are Objects?
An object is a collection of key-value pairs. Keys (also called properties) are strings or Symbols, while values can be anything—strings, numbers, functions, even other objects.
Creating Objects
The most common way to create an object is with curly braces:
const user = {
name: "Sarah",
age: 28,
isDeveloper: true
};
console.log(user.name); // "Sarah"
console.log(user["age"]); // 28
You can also use the Object constructor, though curly braces are preferred:
const empty = new Object(); // Rarely used
Adding and Modifying Properties
Objects are mutable. You can add or change properties anytime:
const person = { name: "Alex" };
// Add new property
person.city = "London";
person["country"] = "UK";
// Modify existing
person.name = "Alexander";
console.log(person);
// { name: "Alexander", city: "London", country: "UK" }
Methods
When a property holds a function, it’s called a method. Methods give objects behavior:
const calculator = {
a: 0,
b: 0,
setValues(x, y) {
this.a = x;
this.b = y;
},
add() {
return this.a + this.b;
},
multiply() {
return this.a * this.b;
}
};
calculator.setValues(5, 3);
console.log(calculator.add()); // 8
console.log(calculator.multiply()); // 15
Object Destructuring
Destructuring lets you extract properties into variables:
const product = {
name: "Laptop",
price: 999,
inStock: true
};
// Old way
const name = product.name;
const price = product.price;
// Destructuring
const { name, price } = product;
console.log(name, price); // "Laptop" 999
What Are Arrays?
An array is an ordered collection of values. Each value has a numeric index starting from 0. Arrays can hold mixed types.
Creating Arrays
const fruits = ["apple", "banana", "cherry"];
const numbers = [1, 2, 3, 4, 5];
const mixed = [1, "hello", true, null];
console.log(fruits[0]); // "apple"
console.log(fruits.length); // 3
Adding and Removing Elements
const colors = ["red", "blue"];
// Add to end
colors.push("green");
colors.push("yellow");
// Add to beginning
colors.unshift("purple");
// Remove from end
const last = colors.pop();
// Remove from beginning
const first = colors.shift();
console.log(colors); // ["blue", "green"]
console.log(first, last); // "purple" "yellow"
Iterating Arrays
There are several ways to loop through arrays:
const scores = [85, 92, 78, 90];
// for loop
for (let i = 0; i < scores.length; i++) {
console.log(scores[i]);
}
// forEach
scores.forEach((score, index) => {
console.log(`Score ${index}: ${score}`);
});
// for...of (modern)
for (const score of scores) {
console.log(score);
}
Essential Array Methods
map() — Transform Each Element
map() creates a new array by transforming each element:
const prices = [100, 200, 300];
// Add tax
const withTax = prices.map(price => price * 1.2);
console.log(withTax); // [120, 240, 360]
// Return objects
const items = ["apple", "banana"];
const objects = items.map((item, i) => ({
id: i + 1,
name: item
}));
// [{ id: 1, name: "apple" }, { id: 2, name: "banana" }]
filter() — Keep Matching Elements
filter() creates a new array with elements that pass a test:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const even = numbers.filter(n => n % 2 === 0);
console.log(even); // [2, 4, 6, 8, 10]
const users = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 17 },
{ name: "Charlie", age: 30 }
];
const adults = users.filter(user => user.age >= 18);
console.log(adults);
// [{ name: "Alice", age: 25 }, { name: "Charlie", age: 30 }]
reduce() — Combine into Single Value
reduce() shrinks an array into a single value:
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 15
// Find maximum
const max = numbers.reduce((a, b) => a > b ? a : b);
console.log(max); // 5
// Group by property
const people = [
{ name: "Alice", dept: "Engineering" },
{ name: "Bob", dept: "Sales" },
{ name: "Charlie", dept: "Engineering" }
];
const byDept = people.reduce((acc, person) => {
if (!acc[person.dept]) {
acc[person.dept] = [];
}
acc[person.dept].push(person.name);
return acc;
}, {});
console.log(byDept);
// { Engineering: ["Alice", "Charlie"], Sales: ["Bob"] }
find() and findIndex()
Find the first matching element:
const products = [
{ id: 1, name: "Laptop", price: 999 },
{ id: 2, name: "Phone", price: 599 },
{ id: 3, name: "Tablet", price: 449 }
];
const found = products.find(p => p.price < 500);
console.log(found); // { id: 3, name: "Tablet", price: 449 }
const index = products.findIndex(p => p.name === "Phone");
console.log(index); // 1
Some and Every
Check conditions across the array:
const scores = [85, 92, 78, 90];
const allPassing = scores.every(s => s >= 70);
console.log(allPassing); // true
const hasPerfect = scores.some(s => s === 100);
console.log(hasPerfect); // false
includes()
Check if an array contains a value:
const fruits = ["apple", "banana", "cherry"];
console.log(fruits.includes("banana")); // true
console.log(fruits.includes("grape")); // false
When to Use Objects vs Arrays
Use Arrays When:
- Order matters (lists, sequences)
- You need to iterate through all elements
- You’re working with collections of similar items
- You need index-based access
const tasks = ["Buy groceries", "Call dentist", "Finish report"];
// Order is important—first task is index 0
Use Objects When:
- You need named keys (associative data)
- You’re mapping identifiers to values
- You need fast lookup by key
- Data has fixed, known properties
const user = {
id: 123,
name: "Sarah",
email: "sarah@example.com"
};
// Fast lookup: user.id, user.name
Combining Both
Real code often mixes objects and arrays:
const orders = [
{
id: 1,
customer: { name: "Alice", email: "alice@test.com" },
items: ["Widget", "Gadget"],
total: 149.99,
status: "shipped"
},
{
id: 2,
customer: { name: "Bob", email: "bob@test.com" },
items: ["Gadget"],
total: 49.99,
status: "pending"
}
];
// Find all shipped orders
const shipped = orders.filter(o => o.status === "shipped");
// Get customer names
const customers = orders.map(o => o.customer.name);
// ["Alice", "Bob"]
Spread Operator with Objects and Arrays
The spread operator (...) copies and combines:
// With arrays
const nums = [1, 2, 3];
const more = [4, 5, 6];
const combined = [...nums, ...more];
console.log(combined); // [1, 2, 3, 4, 5, 6]
// With objects
const defaults = { theme: "light", language: "en" };
const userPrefs = { theme: "dark" };
const settings = { ...defaults, ...userPrefs };
// { theme: "dark", language: "en" }
Modern Array Features
Array Destructuring
const colors = ["red", "green", "blue", "yellow"];
const [first, second] = colors;
console.log(first, second); // "red" "green"
const [head, ...rest] = colors;
console.log(rest); // ["green", "blue", "yellow"]
at() — Negative Indexing
const items = ["a", "b", "c", "d"];
console.log(items.at(-1)); // "d" (last element)
console.log(items.at(-2)); // "c" (second to last)
flat() and flatMap()
const nested = [1, [2, [3, [4]]]];
console.log(nested.flat(2)); // [1, 2, 3, [4]]
console.log(nested.flat(Infinity)); // [1, 2, 3, 4]
// flatMap combines map and flat
const words = ["hello", "world"];
const chars = words.flatMap(word => word.split(""));
console.log(chars); // ["h", "e", "l", "l", "o", "w", "o", "r", "l", "d"]
Summary
Objects store data as key-value pairs—perfect for records with named properties. Arrays store ordered collections—ideal for lists and sequences. Master these fundamentals, and you’ll handle most JavaScript data with confidence.
Key takeaways:
- Use objects for associative data with named keys
- Use arrays for ordered collections
map(),filter(), andreduce()are essential array methods- The spread operator makes copying and combining easy
- You can nest objects and arrays for complex data structures
In the next tutorial, we’ll explore control flow—conditionals and loops that direct your program’s execution.