Object
Key -> Value mapping (no fixed order, you access it by name)
Objects and arrays are the core data structures of JavaScript. Almost every real-world application, from APIs to UI rendering, depends on them.
Understanding how they actually behave in memory is very important for writing code that does not have bugs.
Object
Key -> Value mapping (no fixed order, you access it by name)
Array
A list with index numbers (has a fixed order, you access it by number)
const user = { id: 101, name: "Asha", active: true,};user.name;user["active"];const scores = [80, 92, 75, 99];scores[0]; // 80const user = { name: "Asha" };
// Createuser.age = 22;
// Readuser.name;
// Updateuser.name = "Riya";
// Deletedelete user.age;const arr = [1, 2];
// Createarr.push(3);
// Readarr[0];
// Updatearr[1] = 10;
// Deletearr.pop();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);[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); // 6const user = { name: "Riya", orders: [ { id: 1, price: 100 }, { id: 2, price: 200 }, ],};Destructuring is a quick way to pull values out of an object or array and store them in their own variables.
const user = { name: "Sahil", age: 20 };
const { name, age } = user;const [a, b] = [10, 20];The spread operator (...) is used to copy or expand the items of an array or object.
const arr = [1, 2];const newArr = [...arr, 3];The rest operator also uses ..., but instead of expanding values, it gathers multiple values together into one array.
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); // 10Here, a and b are both pointing to the exact same object in memory. So changing the object through b also changes what you see through a.
A shallow copy only copies the first, outer layer of data. A deep copy goes further and copies everything inside as well, including nested objects.
// for objectsconst copy = { ...obj }; // shallowconst deepCopy = JSON.parse(JSON.stringify(obj)); // deep
// for arraysconst arrCopy = [...arr]; // shallowconst deepArrCopy = arr.map((item) => ({ ...item })); // deep for array of objectsconst arr = [1, 2];const copy = arr;
copy.push(3);Here, arr and copy are both pointing to the exact same memory location, so changing one ends up changing the other as well.