Reputation: 31
What is the need of an anonymous function? I tried searching it out on the web, but I cannot find the optimum solution to this. I have just began exploring jQuery and I'm stuck at this function.
Upvotes: 0
Views: 86
Reputation: 13756
An anonymous function in JavaScript has no name yet it allows you to insert JavaScript code where you normally wouldn't be able to do so.
In example if you want to run some code a few milliseconds (a common problem and fix) later because JavaScript doesn't synchronize as we want often is to use an anonymous function to handle details. By default all you can do is specify a function to call when the timeout finishes however this is extremely limiting because you can't pass parameters to that function...and do you really need a fully-fledged function in those instances to begin with?
By default you can only call another function:
setTimeout(function_name_here,'4000');//Run "function_name_here" after four seconds.
function function_name_here()
{
console.log('Great, how about some parameters so I don\'t have to start using globals?');
}
//We can not declare (parameters) in this situation, lame right?
With an anonymous function we don't have to create another whole dedicated function to handle things if all our code is already available:
var wait_what = 'Cheese it!';
setTimeout(function()
{
console.log('How much code? '+wait_what);//How much code? Cheese it!
alert('All the codes! '+wait_what);//All the codes! Cheese it!
},'4000');
Anonymous functions can even be passed as parameters (you can also submit arrays and objects as parameters).
Additionally I highly recommend avoiding jQuery like the plague as it is a completely unnecessary dependency that only weakens not only your code but also undermines your understanding of JavaScript. You shouldn't force people to download four copies of a 70KB library when the browser they are using already understands JavaScript. You lose performance as well and once you've done enough quality real code you will end up going much faster than someone who has wrought themselves in to maintenance hell.
Upvotes: 1