JavaScript Arrays and Objects
JavaScript Arrays
// Create
const fruits = ["apple", "banana", "cherry"];
const mixed = [1, "two", true, null, { id: 1 }];
// Access
console.log(fruits[0]); // apple
console.log(fruits.length); // 3
// Modify
fruits.push("date"); // add at end
fruits.unshift("avocado"); // add at start
const last = fruits.pop(); // remove from end
const first = fruits.shift(); // remove from start
fruits.splice(1, 1, "mango"); // remove/insert at index
Array Methods
const nums = [1, 2, 3, 4, 5];
// map — transform elements
const doubled = nums.map(n => n * 2); // [2,4,6,8,10]
// filter — select elements
const evens = nums.filter(n => n % 2 === 0); // [2,4]
// reduce — accumulate
const sum = nums.reduce((acc, n) => acc + n, 0); // 15
// find / findIndex
const found = nums.find(n => n > 3); // 4
const idx = nums.findIndex(n => n > 3); // 3
// some / every
nums.some(n => n > 4); // true
nums.every(n => n > 0); // true
// includes
nums.includes(3); // true
// sort
["banana","apple","cherry"].sort(); // alphabetical
nums.sort((a, b) => a - b); // ascending numeric
// flat / flatMap
[[1,2],[3,4]].flat(); // [1,2,3,4]
// forEach (no return value)
nums.forEach(n => console.log(n));
// Spread operator
const copy = [...nums];
const combined = [...nums, 6, 7];
JavaScript Objects
// Object literal
const person = {
name: "Alice",
age: 25,
address: {
city: "Delhi",
pin: "110001"
},
greet() {
return `Hi, I'm ${this.name}`;
}
};
// Access
console.log(person.name); // dot notation
console.log(person["age"]); // bracket notation
console.log(person.address.city); // nested access
console.log(person.greet()); // method call
// Modify
person.age = 26;
person.email = "alice@email.com"; // add property
delete person.email; // delete property
Object Methods
Object.keys(person); // ["name","age","address"]
Object.values(person); // ["Alice", 25, {...}]
Object.entries(person); // [["name","Alice"], ...]
// Spread and merge
const updated = { ...person, age: 27 };
// Destructuring
const { name, age } = person;
const { address: { city } } = person;
Array vs Object
| Feature | Array | Object |
|---|
| Keys | Numeric indices | String keys |
| Ordered | Yes | No (mostly) |
| Use case | Lists | Records/entities |
| Iteration | for...of | for...in |
Key Takeaway: Arrays (ordered lists) and Objects (key-value maps) are the core data structures in JavaScript. Master array methods like map, filter, reduce and object destructuring for clean, functional code.