USE of ForEach in JavaScript
let friends = ['Vasu', 'Mohit', 'Sunil', 'Abhishek'];
// using forEach
friends.forEach(myFunction);
function myFunction(item) {
console.log(item)
}
.
..Output
Vasu
Mohit
Sunil
Abhishek
// For changing in each element or if you want to something random or same value with each Elecment of array - Use below code
let friends = ['Vasu', 'Mohit', 'Sunil', 'Abhishek'];
// using forEach
friends.forEach(myFunction);
function myFunction(item, index, arr) {
arr[index] = 'Hello ' + item;
}
console.log(friends)
..
Output : -
['Hello Vasu', 'Hello Mohit', 'Hello Sunil', 'Hello Abhishek']
FOR vs ForEach both can be used to manipulate Array
const oldArray = ['item1', 'item2', 'item3'];
const newArray = [];
// using for loop
for (let i = 0; i < oldArray.length; i++) {
newArray.push(oldArray[i]);
}
console.log(newArray);
// using forEach
oldArray.forEach(function(item){
newArray.push(item);
})
console.log(newArray);
....
Comments
Post a Comment