Almost every piece of data you touch in JavaScript ends up in one of two shapes: an array, or an object. Get comfortable with both and a surprising amount of everyday JavaScript starts to feel familiar.
Arrays: ordered lists of things
const fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // apple
console.log(fruits.length); // 3
fruits.push("date"); // add to the end
fruits.pop(); // remove from the endLooping over an array
fruits.forEach(fruit => {
console.log(fruit);
});The array methods everyone eventually loves
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
const total = numbers.reduce((sum, n) => sum + n, 0);
console.log(doubled); // [2, 4, 6, 8, 10]
console.log(evens); // [2, 4]
console.log(total); // 15map, filter and reduce look intimidating the first time you see them, but they are worth pushing through. map transforms every item, filter keeps only the ones matching some condition, and reduce collapses the whole array down to a single value. Once these three click, a lot of loops you would have written by hand suddenly become one clean line.
Objects: named properties instead of positions
const person = {
name: "Ann",
age: 30,
};
console.log(person.name); // Ann
console.log(person["age"]); // 30 — also works
person.age = 31; // update a value
person.city = "London"; // add a brand new propertyBoth the dot syntax and the square bracket syntax reach the same value. Dot notation is what you'll use almost all the time; the square bracket version becomes useful when the property name is stored in a variable rather than typed out directly.
Objects inside arrays, arrays inside objects
const users = [
{ name: "Ann", age: 30 },
{ name: "Bob", age: 25 },
];
console.log(users[0].name); // AnnThis combination, an array of objects, is genuinely everywhere in real JavaScript. Data coming back from an API almost always looks exactly like this, so getting comfortable reaching into it, whether that's users[0].name or looping with users.forEach, pays off constantly.
A quick way to tell them apart
If order matters and you're mainly thinking "the first one, the second one, the last one," reach for an array. If you're thinking "the name field, the age field," reach for an object. Most real data ends up being some combination of both, nested inside each other.