Arrays and objects, the two tools you will use forever
Arrays and objects are the bread and dal of JavaScript. Every API response, every form, every cart, every Swiggy order list is one of these two shapes. Learn them well and the rest of the language gets easier.
Most of this lesson is short examples. Read each snippet, then mentally rewrite it for your own use case.
Arrays and the four methods that matter
Say you have a list of Swiggy orders. Each order has a restaurant, total, and a delivered flag.
const orders = [
{ restaurant: 'MTR', total: 320, delivered: true },
{ restaurant: 'Empire', total: 540, delivered: false },
{ restaurant: 'CTR', total: 180, delivered: true },
];maptransforms each item into something new. Same length out.filterkeeps items that pass a test. Shorter array out.reduceboils the whole array down to one value.findreturns the first item that matches, orundefined.
const totals = orders.map(o => o.total);
const pending = orders.filter(o => !o.delivered);
const grandSum = orders.reduce((sum, o) => sum + o.total, 0);
const findMTR = orders.find(o => o.restaurant === 'MTR');Forget
forloops for transformations. Use these four. Your future self will thank you.
Object literals
Objects are key-value pairs. You write them with curly braces.
const user = { name: 'Anil', city: 'Mumbai', upi: 'anil@okhdfc' };Access with dot (user.name) or bracket (user['name']). Bracket is for dynamic keys. Add new keys by assigning: user.phone = '99999...'.
Destructuring is just unpacking
Pulling values out of an object or array into variables, in one line.
const { name, city } = user;
const [first, second] = orders;You can rename: const { name: customerName } = user;. You can set defaults: const { tip = 0 } = order;. You will see this in every React component prop you ever touch.
Spread and rest, the same three dots
The ... operator does opposite things based on context.
- Spread expands an array or object into another.
- Rest collects arguments or remaining properties into one variable.
const moreOrders = [...orders, { restaurant: 'Vidyarthi', total: 90 }];
const userWithPin = { ...user, pincode: '400001' };
function logArgs(first, ...rest) { console.log(first, rest); }Spread is how you make immutable copies of arrays and objects. Rest is how you handle variable arguments cleanly.
JSON, the universal handshake
Every API on the planet talks JSON. JavaScript has two built-in functions for it.
JSON.stringify(obj)turns an object into a string you can send over the network.JSON.parse(str)turns the string back into an object.
const body = JSON.stringify({ orderId: 42, status: 'pending' });
const obj = JSON.parse('{"city":"Delhi"}');If JSON.parse gets bad data, it throws. Wrap it in a try/catch when the source is untrusted.
Quick recap
map,filter,reduce,findcover 90 percent of array work.- Destructure to keep your code flat and readable.
- Spread to copy, rest to gather.
JSON.parseandJSON.stringifyare how you talk to APIs.
Next lesson, the scary one: async and await.
Free tools you can use while you learn
Watching quietly. Tap me if you want a tip.
Try this (0 of 2 done)
- 1
Using reduce, log the total revenue from all orders.
show answer
const sum = orders.reduce((a, o) => a + o.total, 0); console.log(sum); - 2
Map orders to an array of just totals. Log it.
show answer
console.log(orders.map(o => o.total));