Consider this javascript function:
function(){
var someArr = [...];
var someObj = {...};
someArr.forEach(function(item){
if (matchItem(item)){
someObj.callMethod(item.someProp);
}
});
}
Assuming that given code works correctly, let's take a look at it's design. As you can notice, someArr.forEach
is passed a callback function. Meanwhile, object someObj
belongs to the scope of that callback. So from inside the callback function we can manipulate someObj
.
I.e., in this case the callback produces side effects.
We could also bind someObj
to this
object of the callback:
function(){
var someArr = [...];
var someObj = {...};
someArr.forEach(
function(item){
if (matchItem(item)){
this.callMethod(item.someProp);
}
},
someObj
);
}
Again, we are producing some side effects here, though in more explicit manner. In general, this approach can not be considered functional, because it violates the no-side-effects principle.
How should we design code in such situations? Which way is more robust? What are the best practices?
Thank you!