โ
JavaScript Arrays, Objects Array Methods ๐ฆ๐ง
Understanding how arrays and objects work helps you organize, transform, and analyze data in JavaScript. Here's a quick and clear breakdown:
1๏ธโฃ Arrays in JavaScript
An array stores a list of values.
let fruits = ["apple", "banana", "mango"];
console.log(fruits[1]); // banana
โถ๏ธ This creates an array of fruits and prints the second fruit (banana), since arrays start at index 0.
2๏ธโฃ Objects in JavaScript
Objects hold keyโvalue pairs.
let user = {
name: "Riya",
age: 25,
isAdmin: false
};
console.log(user.name); // Riya
console.log(user["age"]); // 25
โถ๏ธ This object represents a user. You can access values using dot (.) or bracket ([]) notation.
3๏ธโฃ Array Methods โ map, filter, reduce
๐น map() โ Creates a new array by applying a function to each item
let nums = [1, 2, 3];
let doubled = nums.map(n => n * 2);
console.log(doubled); // [2, 4, 6]
โถ๏ธ This multiplies each number by 2 and returns a new array.
๐น filter() โ Returns a new array with items that match a condition
let ages = [18, 22, 15, 30];
let adults = ages.filter(age => age >= 18);
console.log(adults); // [18, 22, 30]
โถ๏ธ This filters out all ages below 18.
๐น reduce() โ Reduces the array to a single value
let prices = [100, 200, 300];
let total = prices.reduce((acc, price) => acc + price, 0);
console.log(total); // 600
โถ๏ธ This adds all prices together to get the total sum.
๐ก Extra Notes:
โข map() โ transforms items
โข filter() โ keeps matching items
โข reduce() โ combines all items into one result
๐ฏ Practice Challenge:
โข Create an array of numbers
โข Use map() to square each number
โข Use filter() to keep only even squares
โข Use reduce() to add them all up
๐ฌ Tap โค๏ธ for more!
Post #3178
4.09K
- โค 12