Javascript callback design: is it OK to have side effects? -


consider javascript function:

function(){     var somearr = [...];     var someobj = {...};     somearr.foreach(function(item){         if (matchitem(item)){             someobj.callmethod(item.someprop);         }     }); } 

assuming given code works correctly, let's take @ it's design. can notice, somearr.foreach passed callback function. meanwhile, object someobj belongs scope of callback. inside callback function can manipulate someobj.

i.e., in case callback produces side effects.

we bind someobj this object of callback:

function(){     var somearr = [...];     var someobj = {...};     somearr.foreach(         function(item){             if (matchitem(item)){                 this.callmethod(item.someprop);             }         },         someobj     ); } 

again, producing side effects here, though in more explicit manner. in general, approach can not considered functional, because violates no-side-effects principle.

how should design code in such situations? way more robust? best practices?

thank you!


Comments