Callback Function
A callback function is a function that is passed as an argument to another function and executed later.
<script>
function mainFun(callback){
console.log("main function executed");
callback()
}
function callback(){
console.log("callback function executed");
}
mainFun(callback)
</script>
Output:main function executed
callback function executed
forEach()
The forEach() method calls a function (a callback function) for each array element
It does not return a new array or alter the original array, making it useful for operations like logging or modifying elements in place
Syntax
array.forEach(function(currentValue, index, array) {
// action
});
let fruits=["apple","orange","mango","banana"]
fruits.forEach(fru)
function fru(i,j,k){
console.log("Fruits are Healthy",i,j,k)
}
Output:Fruits are Healthy apple 0 [ 'apple', 'orange', 'mango', 'banana' ]
Fruits are Healthy orange 1 [ 'apple', 'orange', 'mango', 'banana' ]
Fruits are Healthy mango 2 ['apple', 'orange', 'mango', 'banana' ]
Fruits are Healthy banana 3 [ 'apple', 'orange', 'mango', 'banana' ]
let fruits=["apple","orange","mango","banana"]
fruits.forEach((fru)=>{
console.log(fru.toUpperCase())
})
Output:APPLE
ORANGE
MANGO
BANANA
let fruits=["apple","orange","mango","banana"]
let fru=fruits.forEach((f)=>{
return f.toUpperCase()
})
console.log(fru);
Output:undefined
map()
It creates a new array by applying a specified function to each element of the original array
It returns a new array with the transformed values, leaving the original array unchanged
Syntax
array.map(function(currentValue, index, array) {
return newValue;
});
let fruits=["apple","orange","mango","banana"]
let fru=fruits.map((f)=>{
return f.toUpperCase()
})
console.log(fru);
Output:[ 'APPLE', 'ORANGE', 'MANGO', 'BANANA' ]
let fruits=["apple","orange","mango","banana"]
fruits.map((fru)=>{
console.log(fru.toUpperCase())
})
Output:APPLE
ORANGE
MANGO
BANANA
Difference between map() and forEach()

Top comments (0)