종우공간 2021. 7. 30. 04:45

forEach

const cars = ['Ford', 'Chevy', 'Honda', 'Toyota'];

cars.forEach(function(car, index, array) { //takes three params
    console.log(`${index} : ${car}`);
    console.log(array);
});

- it is used to loop through the array

- forEach takes the anonymous function with three parameters

- it is much cleaner over normal for loop

map

const users = [
    {id:1, name:'John'},
    {id:2, name:'Sara'},
    {id:3, name:'James'}
];

const ids = users.map(function(user) {
    return user.id;
});

console.log(ids); //yields [1, 2, 3]

- it is used to loop through the array with objects in it

- map takes the anonymous function with one parameter of each object in the array

- 'return' is used to populate the needed data

for in

const user = {
    firstName: 'John',
    lastName: 'Doe',
    age: 40
}

for(let x in user) {
    console.log(`${x} : ${user[x]}`); //x yields each key of the object
}

- it is used to loop through the object

- in the above example code, x takes each key of the object