for…of, filter and map for…of, filter और map
Lesson 7 of 15 · about 14 minutes · Simpler loops, picking items, changing every item.
⚡ 0 XP
Step 1 of 2
The for…of loop
When you just need each value (not the index), for...of is simpler:
for (const city of cities) { ... } — city is each item in turn- It works on strings too:
for (const ch of "Pune") gives P, u, n, e
A string method you will use here: "aeiou".includes(ch) is true when ch is a vowel.
Exampleconst snacks = ["samosa", "vada pav", "dhokla"];
for (const s of snacks) {
console.log(`I love ${s}`);
}
🎯 Challenge: Counting with for…of +15 XP
Using for...of loops:
- Count the vowels (a, e, i, o, u) in
city and store the count in vowels. - Add up the lengths of all names in
cities and store it in letters.
Try twice to unlock the solution (0/2)
script.jsCtrl ⏎
Console
Output from console.log appears here.
Checklist
Press Run to check your code.
- ○
vowels is 7
- ○
letters is 16
- ○
for…of is used
Lesson notes (text version)
1. The for…of loop
When you just need each value (not the index), for...of is simpler:
for (const city of cities) { ... } — city is each item in turn- It works on strings too:
for (const ch of "Pune") gives P, u, n, e
A string method you will use here: "aeiou".includes(ch) is true when ch is a vowel.
const snacks = ["samosa", "vada pav", "dhokla"];
for (const s of snacks) {
console.log(`I love ${s}`);
}
Challenge: Counting with for…of
Using for...of loops:
- Count the vowels (a, e, i, o, u) in
city and store the count in vowels. - Add up the lengths of all names in
cities and store it in letters.
2. filter and map
Two array methods save a lot of loops. Both take a tiny function written with an arrow =>:
filter keeps only the items that pass a test: marks.filter(m => m >= 33) keeps the passing marksmap changes every item and gives a new array of the same length: prices.map(p => p * 2) doubles every price
Read m => m >= 33 as “for each m, is m at least 33?”. The original array is not changed.
const prices = [120, 450, 80, 999];
const cheap = prices.filter(p => p < 200);
const inPaise = prices.map(p => p * 100);
console.log(cheap); // [120, 80]
console.log(inPaise); // [12000, 45000, 8000, 99900]
Challenge: Who passed? Add grace marks
Using the marks array:
passed: only the marks that are 33 or more (use filter)withGrace: every mark plus 5 grace marks (use map)