| Arrays & Objects in JavaScript | Javascript object and Properties | |
Arrays & Methods in JavaScript |
They let you store ordered collections of values and then process them with powerful built-in methods. Letβs go step by step.
// Using array literal let fruits = ["apple", "banana", "cherry"]; // Using Array constructor let numbers = new Array(10, 20, 30); // Empty array let empty = [];
β Arrays can hold any type: numbers, strings, objects, even other arrays.
Executes a function for each element in the array. Does not return a new array (returns undefined).
let fruits = ["apple", "banana", "cherry"]; fruits.forEach(fruit => console.log(fruit)); // apple // banana // cherry
Transforms each element and returns a new array of the same length.
let numbers = [1, 2, 3, 4]; let squares = numbers.map(n => n * n); console.log(squares); // [1, 4, 9, 16]
Returns a new array with elements that pass a condition.
let numbers = [5, 12, 8, 130, 44]; let bigNumbers = numbers.filter(n => n > 10); console.log(bigNumbers); // [12, 130, 44]
Reduces the array to a single value by applying a function.
let numbers = [1, 2, 3, 4, 5]; let sum = numbers.reduce((acc, curr) => acc + curr, 0); console.log(sum); // 15
forEach() β executes a function for each element (no return value).map() β transforms elements and returns a new array.filter() β returns a new array with elements that meet a condition.reduce() β combines all elements into a single result (sum, average, etc.).| Method | Returns | Use Case |
|---|---|---|
| forEach | undefined | Perform side effects (logging, updating external vars) |
| map | New array | Transform each element (e.g., square numbers) |
| filter | New array | Select elements that meet a condition |
| reduce | Single value | Accumulate into one result (sum, product, max, etc.) |
let students = [
{ name: "Alice", marks: 85 },
{ name: "Bob", marks: 45 },
{ name: "Charlie", marks: 72 },
{ name: "David", marks: 90 }
];
// 1. Print all names
students.forEach(s => console.log(s.name));
// 2. Get array of marks squared
let squaredMarks = students.map(s => s.marks * s.marks);
// 3. Filter students who passed (>= 50)
let passed = students.filter(s => s.marks >= 50);
// 4. Calculate average marks
let total = students.reduce((acc, s) => acc + s.marks, 0);
let average = total / students.length;
console.log("Squared Marks:", squaredMarks);
console.log("Passed Students:", passed);
console.log("Average Marks:", average);
π Arrays + these methods = functional programming power in JavaScript. They let you write clean, declarative code instead of messy loops.
| Arrays & Objects in JavaScript | Javascript object and Properties | |