Skip to content

Objects and Arrays

Objects and arrays are the core data structures of JavaScript. Almost every real-world application—from APIs to UI rendering—depends on them.

  • Objects represent structured data with named fields
  • Arrays represent ordered collections of values

Understanding how they behave in memory is critical for writing bug-free code.


Object

Key → Value mapping (unordered, named access)

Array

Indexed list (ordered, numeric access)

graph LR A[Data Structure Decision] --> B{Need Named Fields?} B -->|Yes| C[Object] B -->|No| D{Ordered List?} D -->|Yes| E[Array]

const user = {
id: 101,
name: "Asha",
active: true,
};
user.name;
user["active"];

graph TD A[user object] --> B[id: 101] A --> C[name: Asha] A --> D[active: true]

const scores = [80, 92, 75, 99];
scores[0]; // 80

graph TD A[Array] --> B[index 0 → 80] A --> C[index 1 → 92] A --> D[index 2 → 75]

const user = { name: "Asha" };
// Create
user.age = 22;
// Read
user.name;
// Update
user.name = "Riya";
// Delete
delete user.age;

for (let key in user) {
console.log(key, user[key]);
}
arr.forEach((value) => console.log(value));

Object.keys(obj);
Object.values(obj);
Object.entries(obj);

arr.map(fn);
arr.filter(fn);
arr.reduce(fn);
arr.find(fn);
arr.some(fn);
arr.every(fn);

graph LR A[Array] --> B[map → transform] A --> C[filter → select] A --> D[reduce → aggregate]

[1, 2, 3]
.map((x) => x * 2) // [2,4,6]
[(1, 2, 3)].filter((x) => x > 1) // [2,3]
[(1, 2, 3)].reduce((a, b) => a + b, 0); // 6

const user = {
name: "Riya",
orders: [
{ id: 1, price: 100 },
{ id: 2, price: 200 },
],
};

graph TD A[user] --> B[name] A --> C[orders array] C --> D[obj1] C --> E[obj2]

const user = { name: "Sahil", age: 20 };
const { name, age } = user;
const [a, b] = [10, 20];

const arr = [1, 2];
const newArr = [...arr, 3];
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}

const a = { x: 1 };
const b = a;
b.x = 10;
console.log(a.x); // 10

graph LR A[a] --> C[Memory Object] B[b] --> C

// for objects
const copy = { ...obj }; // shallow
const deepCopy = JSON.parse(JSON.stringify(obj)); // deep
// for arrays
const arrCopy = [...arr]; // shallow
const deepArrCopy = arr.map((item) => ({ ...item })); // deep for array of objects

  1. Use object for structured data (user, product)
  2. Use array for collections (list of items)
  3. Use array of objects for APIs
  4. Avoid mutating shared references

const arr = [1, 2];
const copy = arr;
copy.push(3);

Both point to same memory.