Introduction
Welcome to Part 8 of the JavaScript for Beginners Series. In this part, we explore Array Methods. In modern JavaScript (and especially in React), we rarely use for loops to process lists. Instead, we use Higher Order Functions that result in cleaner, more readable code.
- Darija: هاد الـ Methods بـ 3 هوما الساروت باش تخدم بـ Arrays بطريقة احترافية (Functional Programming). فـ React، غادي تخدم بيهم بزاف باش تأفيشي (Display) القوائم.
1. .map() (Transform)
Creates a new array by applying a function to every element in the calling array. It is used to transform data (e.g., converting raw data into HTML).
- Darija: كتخدم بيها إيلا بغيتي تدوز على الـ Elements كاملين وتبدل فيهم شي حاجة (مثلاً عندك قائمة د الأسعار وبغيتي تزيد عليهم الضريبة). هي "كتحول" الداتا من شكل لشكل آخر.
2. .filter() (Select)
Creates a new array with only the elements that pass a specific test (return true).
- Darija: كتخدم بيها إيلا بغيتي "تصفي" الداتا. كتقول ليها "عطيني غير المنتوجات اللي الثمن ديالهم كبر من 200 درهم"، وهي كترجع ليك Array جديد فيه غير داكشي اللي بغيتي.
3. .reduce() (Accumulate)
Executes a reducer function on each element, resulting in a single output value (like a sum).
- Darija: كتجمع ليك الحساب كامل فـ قيمة وحدة (مثلاً إيلا بغيتي تحسب الطوطال ديال شي Panier).
Code Examples
Here is how you use them in practice:
const prices = [100, 200, 300, 400]; // 1. MAP: Double the prices // Returns a NEW array, does not change the original const doubled = prices.map(price => price * 2); console.log(doubled); // Output: [200, 400, 600, 800] // 2. FILTER: Get prices above 250 const expensive = prices.filter(price => price > 250); console.log(expensive); // Output: [300, 400] // 3. REDUCE: Calculate the Total // 'acc' is the accumulator (total), 'curr' is the current item // '0' is the initial value const total = prices.reduce((acc, curr) => acc + curr, 0); console.log(total); // Output: 1000
