0% found this document useful (0 votes)
45 views6 pages

Important Array Methods

This document provides detailed notes on essential array methods (map, filter, reduce), modern operators (||, &&, ?, ??), and conditional rendering in React. It includes key points, common mistakes, examples, and practical questions for different skill levels. Additionally, it offers memory techniques and best practices for using these methods and operators effectively in React applications.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views6 pages

Important Array Methods

This document provides detailed notes on essential array methods (map, filter, reduce), modern operators (||, &&, ?, ??), and conditional rendering in React. It includes key points, common mistakes, examples, and practical questions for different skill levels. Additionally, it offers memory techniques and best practices for using these methods and operators effectively in React applications.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

🎯 Important Array Methods, Modern Operators

& React Patterns 🚀 🚀


📘 Detailed Notes on map , filter , reduce , || , && , ?. , ?? , and
Conditional Rendering
Created by: Neeraj | LinkedIn: neeraj-kumar1904 💼 | X: @_19_neeraj 🐦 | GitHub:
Neeraj05042001 🐙 |

1. map() 🗺️
Purpose: Transform each element in an array → returns a new array.
Key Points:
Always returns an array of the same length. 📏
Pure function → doesn't mutate the original array. ✨
React Use: Rendering lists of components. ⚛️
Common Mistake: Forgetting to return inside callback. ⚠️

✅ Example:

[1, 2, 3].map(n => n * 2); // [2, 4, 6]

{[Link](user => <UserCard key={[Link]} name={[Link]} />)}

💡 Quick Tip: Always remember the key prop when mapping in React!

2. filter() 🔍
Purpose: Select elements that pass a condition → returns a new array.
Key Points:
May return an empty array. 📦
Good for search, conditionally showing items. 🔎
React Use: Filtering lists before mapping them. ⚛️
Common Mistake: Using map when filter is needed. ❌

✅ Example:
[1, 2, 3, 4].filter(n => n % 2 === 0); // [2, 4]

💡 Memory Trick: Filter = "Sieve" - keeps what passes through!

3. reduce() ⚡
Purpose: Reduce array to a single value (number, object, string, etc.).
Key Points:
Takes an accumulator ( acc ) and current value ( curr ). 🔄
Often used for sums, averages, counts, grouping. 📊
React Use: Calculate cart total, analytics. 💰
Common Mistake: Forgetting the initial value. ⚠️

✅ Example:

[1, 2, 3, 4].reduce((acc, curr) => acc + curr, 0); // 10

💡 Interview Tip: Reduce can replace both map AND filter in complex scenarios!

4. Logical OR ( || ) 🔀

Purpose: Returns the first truthy value OR last value.


Key Points: Often used for default values. 🎯
Common Mistake: Misusing with 0 or "" . ⚠️

✅ Example:

"" || "Guest"; // "Guest"

🔥 Interview Alert: Know the falsy values: false , 0 , "" , null , undefined , NaN

5. Logical AND ( && ) ✅

Purpose: Returns first falsy value OR last value.


React Use: Conditional rendering (only render if condition true). ⚛️

✅ Example:
{isLoggedIn && <button>Logout</button>}

💡 Pro Pattern: Use && for "show if true", use ternary for "show A or B"

6. Optional Chaining ( ?. ) 🛡️

Purpose: Safely access nested properties.


Key Points: Returns undefined if property doesn't exist instead of throwing error. 🚫💥

✅ Example:

const user = { profile: { name: "Neeraj" } };


[Link]?.name; // "Neeraj"
[Link]?.city; // undefined

🎯 Interview Gold: This prevents the dreaded "Cannot read property of undefined" error!

7. Nullish Coalescing ( ?? ) 🎭
Purpose: Provide fallback only if value is null or undefined (NOT other falsy values).
Difference from || :
0 || 5 → 5 🔄
0 ?? 5 → 0 🎯
✅ Example:

const count = 0 ?? 10; // 0

🔥 Critical Distinction: ?? only checks for null / undefined , while || checks all falsy values!

8. Conditional Rendering ( ?: ) 🔀

Purpose: Inline if/else rendering.


Common in React: Toggle between two UIs. 🔄

✅ Example:
{isLoggedIn ? <Dashboard /> : <Login />}

💡 Best Practice: Use ternary for A-or-B scenarios, && for show-or-nothing scenarios

🎯 10 Practice Questions (Basic → Advanced)


📚 Basic Level (Foundations)
1️⃣ Use map() to square all numbers in [2, 4, 6, 8] .

2️⃣ Use filter() to return only even numbers from [1, 2, 3, 4, 5, 6] .

3️⃣ Use reduce() to find the sum of [10, 20, 30, 40] .

4️⃣ Explain difference between || and ?? with an example where they


behave differently.

5️⃣ Render a list of users in React:


const users = ["Alice", "Bob", "Charlie"];

⚡ Intermediate Level (Building Skills)


6️⃣ You have an array of products:
const products = [
{ id: 1, name: "Shirt", price: 500, inStock: true },
{ id: 2, name: "Shoes", price: 2000, inStock: false },
{ id: 3, name: "Cap", price: 300, inStock: true },
];

Show only in-stock products using filter + map .


Calculate total cost of in-stock products using reduce .

7️⃣ Use optional chaining ( ?. ) to safely get [Link] from:


const user = { name: "Neeraj", address: { city: "Delhi" } };
const user2 = { name: "Rahul" };

8️⃣ Implement conditional rendering in React:


If isLoggedIn = true , show "Welcome Neeraj".
Else, show "Please log in".

🔥 Advanced Level (Interview Ready)


9️⃣ Given:
const cart = [
{ item: "Shirt", price: 500, qty: 2 },
{ item: "Shoes", price: 2000, qty: 1 },
{ item: "Cap", price: 300, qty: 3 },
];

Use reduce to calculate the total price of cart.


Then, render it in React.

🔟 Build a search filter component in React:


Input box for search text.
A list of products.
Use filter + map to show only matching products.
Use ?? to show "No products found" if filter returns empty.

🎓 Extra Interview Power-Ups ⭐


🧠 Memory Techniques:
MAP = "Transform each" 🔄
FILTER = "Keep only matching" 🔍
REDUCE = "Combine into one" ⚡

📋 Common Interview Patterns:


Chaining: [Link]().map().reduce() 🔗
Error Prevention: Always use ?. for nested objects 🛡️

🎯 React Best Practices:


Always provide key prop in lists 🔑
Use && for conditional rendering 🎭
Prefer ?? over || for default values 🎯

Visit My Repo for more

You might also like