spence911 Posted March 22, 2014 Share Posted March 22, 2014 I'm a newbie to JavaScript and I'm trying to wrap my head around anonymous functions. I understand how to create one but what is not clear is the purpose. Why make a function anonymous when it does the same job perfectly without being anonymous? Link to comment https://forums.phpfreaks.com/topic/287178-what-is-the-purpose-of-anonymous-functions/ Share on other sites More sharing options...
kicken Posted March 22, 2014 Share Posted March 22, 2014 They have two primary uses: 1. As a callback for another function and 2. To create a closure A lot of the time for a callback, you only need a small couple of lines function. Rather than creating named functions for all these callbacks, it's far easier (and more reader-friendly typically) to just do a short anonymous function. For example: $('.something').each(function(idx,ele){ console.log(ele); //do something with each element }); //or $('.something').slideUp(function(){ console.log('done sliding'); //Do something when the animation finishes }); If you didn't use anonymous functions you'd either have to name them every function, or change the code, for example: function dotSomethingIterationBody(idx,ele){ console.log(ele); //do something with each element } function dotSomethingAnimationFinished(){ console.log('done sliding'); //Do something when the animation finishes } { $('.something').each(dotSomethingIterationBody); //or change to a loop for (var idx=0,items=$('.something'); idx<items.length; idx++){ var ele = items[idx]; console.log(ele); //do something with each element } } $('.something').slideUp(dotSomethingAnimationFinished); In a large application it is simply impractical to try and name every function like that. Link to comment https://forums.phpfreaks.com/topic/287178-what-is-the-purpose-of-anonymous-functions/#findComment-1473529 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.