JavaScript Arrays and Objects
Master JavaScript arrays and objects - the primary data structures used in React. Learn array methods, object manipulation, and destructuring.
Topics Covered:
Prerequisites:
- JavaScript Functions and Scope
Video Tutorial
Overview
Arrays and objects are the primary data structures in JavaScript and React. You'll use them constantly - arrays for lists of data, objects for structured data. This tutorial covers creating and manipulating arrays and objects, essential array methods (map, filter, reduce), object methods, destructuring, and the spread operator. These concepts are fundamental to React development.
Working with Arrays
Arrays store ordered collections of values. They're essential for rendering lists in React. Array Creation: • Array literal: [1, 2, 3] • Array constructor: new Array() • Can contain any data types • Zero-indexed (first item is index 0) Array Properties: • length - Number of elements • Access elements with bracket notation • Arrays are mutable Common Operations: • Access elements by index • Modify elements • Add/remove elements • Iterate over elements
// Creating arrays
const numbers = [1, 2, 3, 4, 5];
const fruits = ["apple", "banana", "orange"];
const mixed = [1, "hello", true, null];
// Accessing elements
console.log(fruits[0]); // "apple"
console.log(fruits[1]); // "banana"
console.log(fruits.length); // 3
// Modifying arrays
fruits[0] = "grape";
console.log(fruits); // ["grape", "banana", "orange"]
// Adding elements
fruits.push("mango"); // Add to end
fruits.unshift("kiwi"); // Add to beginning
console.log(fruits); // ["kiwi", "grape", "banana", "orange", "mango"]
// Removing elements
fruits.pop(); // Remove from end
fruits.shift(); // Remove from beginning
console.log(fruits); // ["grape", "banana", "orange"]
// Iterating over arrays
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// for...of loop (modern)
for (const fruit of fruits) {
console.log(fruit);
}
// Arrays in React (preview)
function FruitList() {
const fruits = ["apple", "banana", "orange"];
return (
<ul>
{fruits.map(fruit => (
<li key={fruit}>{fruit}</li>
))}
</ul>
);
}Arrays store ordered collections. Access elements by index (starting at 0). Arrays are mutable - you can modify them. Arrays are essential for rendering lists in React.
Essential Array Methods
JavaScript provides powerful array methods that are essential for React development. These methods create new arrays without mutating the original. Important Array Methods: • map() - Transform each element • filter() - Select elements that match condition • reduce() - Combine elements into single value • find() - Find first matching element • forEach() - Execute function for each element • includes() - Check if array contains value • slice() - Extract portion of array • concat() - Combine arrays Why These Matter: • Used constantly in React • Functional programming style • Don't mutate original array • Return new arrays
const numbers = [1, 2, 3, 4, 5];
// map() - Transform each element
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// filter() - Select matching elements
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // [2, 4]
// reduce() - Combine into single value
const sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // 15
// find() - Find first matching element
const found = numbers.find(num => num > 3);
console.log(found); // 4
// forEach() - Execute for each element
numbers.forEach(num => console.log(num));
// includes() - Check if contains value
console.log(numbers.includes(3)); // true
console.log(numbers.includes(10)); // false
// slice() - Extract portion
const firstThree = numbers.slice(0, 3);
console.log(firstThree); // [1, 2, 3]
// Array methods in React (preview)
function UserList({ users }) {
// Filter active users
const activeUsers = users.filter(user => user.isActive);
// Map to JSX elements
return (
<ul>
{activeUsers.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
// Chaining array methods
const result = numbers
.filter(num => num > 2)
.map(num => num * 2)
.reduce((sum, num) => sum + num, 0);
console.log(result); // 24 (3*2 + 4*2 + 5*2)Array methods like map, filter, and reduce are essential for React. They don't mutate the original array and return new arrays. These methods are used constantly in React for transforming and filtering data.
Working with Objects
Objects store key-value pairs and represent structured data. They're fundamental to JavaScript and React. Object Creation: • Object literal: { key: value } • Object constructor: new Object() • Keys are strings (or symbols) • Values can be any type Accessing Properties: • Dot notation: obj.property • Bracket notation: obj['property'] • Use bracket notation for dynamic keys Object Methods: • Object.keys() - Get all keys • Object.values() - Get all values • Object.entries() - Get key-value pairs • Object.assign() - Copy properties
// Creating objects
const user = {
name: "Alice",
age: 30,
email: "alice@example.com"
};
// Accessing properties
console.log(user.name); // "Alice"
console.log(user["age"]); // 30
// Dynamic property access
const key = "email";
console.log(user[key]); // "alice@example.com"
// Adding properties
user.city = "New York";
user["country"] = "USA";
// Modifying properties
user.age = 31;
// Nested objects
const user = {
name: "Alice",
address: {
street: "123 Main St",
city: "New York"
}
};
console.log(user.address.city); // "New York"
// Object methods
const keys = Object.keys(user); // ["name", "age", "email"]
const values = Object.values(user); // ["Alice", 30, "alice@example.com"]
const entries = Object.entries(user); // [["name", "Alice"], ["age", 30], ...]
// Objects in React (preview)
function UserCard({ user }) {
return (
<div>
<h2>{user.name}</h2>
<p>Age: {user.age}</p>
<p>Email: {user.email}</p>
</div>
);
}Objects store key-value pairs. Use dot notation or bracket notation to access properties. Objects are essential for representing structured data in React components.
Destructuring Arrays and Objects
Destructuring allows you to extract values from arrays and objects into variables. It's heavily used in React. Array Destructuring: • Extract values by position • Skip values with commas • Use rest operator for remaining Object Destructuring: • Extract by property name • Rename with alias • Default values • Nested destructuring Why It's Important: • Used extensively in React • Cleaner code • Easier to work with props • Functional programming style
// Array destructuring
const numbers = [1, 2, 3];
const [first, second, third] = numbers;
console.log(first); // 1
console.log(second); // 2
// Skip values
const [a, , c] = numbers; // Skip second value
console.log(a, c); // 1, 3
// Rest operator
const [first, ...rest] = numbers;
console.log(first); // 1
console.log(rest); // [2, 3]
// Object destructuring
const user = {
name: "Alice",
age: 30,
email: "alice@example.com"
};
const { name, age } = user;
console.log(name); // "Alice"
console.log(age); // 30
// Rename variables
const { name: userName, age: userAge } = user;
console.log(userName); // "Alice"
// Default values
const { name, age, city = "Unknown" } = user;
console.log(city); // "Unknown"
// Nested destructuring
const user = {
name: "Alice",
address: {
city: "New York",
country: "USA"
}
};
const { address: { city, country } } = user;
console.log(city); // "New York"
// Destructuring in React (preview)
function UserCard({ name, age, email }) {
// Instead of: const name = props.name;
return (
<div>
<h2>{name}</h2>
<p>{age} years old</p>
<p>{email}</p>
</div>
);
}
// Destructuring function parameters
function greet({ name, greeting = "Hello" }) {
console.log(`${greeting}, ${name}!`);
}
greet({ name: "Alice" }); // "Hello, Alice!"Destructuring extracts values from arrays and objects. It's used extensively in React for props, state, and function parameters. Makes code cleaner and more readable.
Spread Operator
The spread operator (...) expands arrays and objects. It's essential for React state management. Spread Operator Uses: • Copy arrays/objects • Combine arrays/objects • Pass array elements as arguments • Add properties to objects Why It's Important: • Essential for React state updates • Immutability in React • Combining data • Creating new arrays/objects
// Spread with arrays
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4, 5, 6]
// Copy array
const original = [1, 2, 3];
const copy = [...original];
copy.push(4);
console.log(original); // [1, 2, 3] (unchanged)
console.log(copy); // [1, 2, 3, 4]
// Spread with objects
const user = { name: "Alice", age: 30 };
const updated = { ...user, age: 31 };
console.log(updated); // { name: "Alice", age: 31 }
// Combine objects
const defaults = { theme: "light", language: "en" };
const userPrefs = { theme: "dark" };
const merged = { ...defaults, ...userPrefs };
console.log(merged); // { theme: "dark", language: "en" }
// Spread in function calls
const numbers = [1, 2, 3];
console.log(Math.max(...numbers)); // 3
// Spread in React (preview)
function Component() {
const [user, setUser] = useState({ name: "Alice", age: 30 });
const updateAge = () => {
// Create new object instead of mutating
setUser({ ...user, age: user.age + 1 });
};
return <button onClick={updateAge}>Age: {user.age}</button>;
}
// Adding to array in React
function TodoList() {
const [todos, setTodos] = useState([]);
const addTodo = (newTodo) => {
// Create new array instead of mutating
setTodos([...todos, newTodo]);
};
}The spread operator creates copies and combines arrays/objects. Essential for React state updates - always create new objects/arrays instead of mutating existing ones.
Conclusion
Arrays and objects are the primary data structures in JavaScript and React. You've learned array methods (map, filter, reduce), object manipulation, destructuring, and the spread operator. These concepts are used constantly in React - for rendering lists, managing state, handling props, and more. Practice these operations until they become second nature. Next, you'll learn about asynchronous JavaScript, which is essential for fetching data in React applications.