-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiterators-forEach.js
65 lines (49 loc) · 1.66 KB
/
iterators-forEach.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Iterators: .forEach() Method
// The forEach() method executes a provided function once for each array element.
// .forEach() takes an argument of callback function.
// .forEach() loops through the array and executes the callback function for each element. During each execution, the current element is passed as an argument to the callback function.
// The return value for .forEach() will always be UNDEFINED
// Ex 1
const fruits = ['mango', 'papaya', 'pineapple', 'apple'];
// Iterate over fruits below
// Method 1: Arrow function syntax
fruits.forEach(fruit => console.log(`I want to eat a ${fruit}`));
// Method 2: Writing the callback function separately
function printFruit(fruit) {
console.log(`I want to eat a ${fruit}`);
}
fruits.forEach(printFruit);
// Both methods return:
// I want to eat a mango
// I want to eat a papaya
// I want to eat a pineapple
// I want to eat a apple
// fruits.forEach() calls the forEach method on the fruits array.
// Ex 2
const veggies = ["broccoli", "spinach", "cauliflower", "broccoflower"];
const politelyDecline = (veg) => {
console.log("No " + veg + " please. I will have pizza with extra cheese.");
};
// Write your code here:
const declineEverything = veg => {
veg.forEach(politelyDecline);
};
const acceptEverything = arr => {
arr.forEach(el => {
console.log("Ok, I guess I will eat some " + el + ".");
});
};
acceptEverything(veggies);
declineEverything(veggies);
// capAllElements
function capAllElements(arr){
try {
arr.forEach((el, index, array) => {
array[index] = el.toUpperCase();
console.log(el, index, array);
});
} catch(e) {
console.log(e);
}
}
capAllElements('Incorrect argument');