So I had an interview where I was asking the purpose of declaring and calling a function immideately, and i couldn't answer it, i.e:
(function(){
// code
})();
What's the reason for doing this?
Object-Oriented JavaScript - Second Edition: One good application of immediate (self-invoking) anonymous functions
is when you want to have some work done without creating extra global
variables. A drawback, of course, is that you cannot execute the same
function twice. This makes immediate functions best suited for one-off
or initialization tasks.
The syntax may look a little scary at first, but all you do is simply
place a function expression inside parentheses followed by another set
of parentheses. The second set says "execute now" and is also the
place to put any arguments that your anonymous function might accept:
(function() {
})();
or
(function() {
}());
are the same:
Related
I've seen IIFE's written:
(function() {
console.log("do cool stuff");
})();
as well as:
(function() {
console.log("do more cool stuff");
}());
They seem to work the same in any context I've used them, though in cases I've been told one way is right and the other is wrong, vice versa. Does anyone have any solid reason or logic as to it being written one order over the other? Is there some cases where there could be potentially more going on after the function body closes but before the invoking parenthesis come into play, or after but before that final closing parenthesis? I've mostly used these in an Angular module closures and can't seem to find anything on any real reason to go one way or the other, wondering if anyone had different experience.
Short answer: It doesn't matter, as long as you put them there.
Long answer: It doesn't matter except in the case of arrow functions, because for JavaScript the only important thing is that they are there. The reason for this is that the language spec defines that a statement must only start with the function keyword if you declare a named function. Hence, it is against the spec to define an IIFE like that:
function () {}();
The workaround for this is to wrap the entire thing in parentheses, so that the statement does not start with the function keyword anymore. You achieve this by using
(function () {})();
as well as by using:
(function () {}());
Which one you choose is completely arbitrary and hence up to you.
I (personally) put the parentheses around the function, not around the call, i.e. like this one:
(function () {})();
Reason: I want to use the smallest portion of code to be wrapped in something that is only needed for technical reasons, and this is the function definition, not the call. Apart from that the spec says that you can not define a function in that way, it is not about calling the function. Hence, I think it's more clear if you wrap the definition, not the call.
edit
However, in the case of the arrow function in es6, the invocation must be outside of the wrapper. It being inside the wrapper causes an unexpected token error on the opening parenthesis of the invocation. Not totally clear on the mechanics of why this is so.
From what I have read from other topics about the issuse SIAFs or Self Invoking Anonymous Functions are simply there to serve as a container, and it limits the scope of variables (from what I have learnt). Now, the question is, why can I do this:
$("ul>li").click((function(){
}));
But not add another SIAF after it? Like so:
$("ul>li").click((function(){
}));
(function(){
});
It is weird to me, as this, just the SIAF on its own gives me no errors in the IDE:
$("ul>li").click((function(){
}));
(function(){
});
This:
(function() { .. });
is a no-op expression, and in particular it does not involve a function call. A function object is instantiated but it's not used in any way.
This:
(function() { ... })();
does do something, because the trailing () causes the function to be invoked. (It doesn't invoke itself.)
In JavaScript, a reference to a function is just a value, and a function is just an object (well, a special object). When a reference to a function is followed by a parenthesized list of values, then that's a function call. It doesn't matter where the reference to the function comes from. (Where it comes from can affect the semantics of the function call, but not the basic fact of the function call itself.)
edit — the terminology "self-invoking function expression" has gained some currency. I won't wade into a dispute, but in my opinion it's less accurate than the alternative "immediately-invoked function expression" because really a function can't invoke itself externally. It can include a call to itself, but that's a different thing entirely. However I understand the spirit of the term and I think it's harmless.
I observe a different (different for me) way to write function of javascript or jquery,,,you guys kindly guide me about the working of this one.
(function ()
{
//some statements of javascript are sitting here
//some statements of javascript are sitting here
//some statements of javascript are sitting here
//some statements of javascript are sitting here
//some statements of javascript are sitting here
}());
Truly I'm not understanding (function(){}());.
No one is calling it but it is being called properly.
If any piece of tutorial you guys know, concerned to it, then tell me.
That is a Immediately-Invoked Function Expression (IIFE). In other words, a function that gets executed when defined
Declaring a function without a name is normally used to assign that function into a variable. A useful trick which allows you to pass the entire function around and call it later.
In this case it's not being assigned to anything, but the extra set of brackets after the braces are effectively calling the function immediately.
Can someone please explain the differences between the following functions:
(function($){
// can do something like
$.fn.function_name = function(x){};
})(jQuery);
Could I use jQuery in the next function?
(function(){
}());
And is the following the same as jquery.ready()?
$(function(){
});
Thanks!
(function($){
// can do something like
$.fn.function_name = function(x){};
})(jQuery);
That is self-executing anonymous function that uses $ in argument so that you can use it ($) instead of jQuery inside that function and without the fear of conflicting with other libraries because in other libraries too $ has special meaning. That pattern is especially useful when writing jQuery plugins.
You can write any character there instead of $ too:
(function(j){
// can do something like
j.fn.function_name = function(x){};
})(jQuery);
Here j will automatically catch up jQuery specified at the end (jQuery). Or you can leave out the argument completely but then you will have to use jQuery keyword all around instead of $ with no fear of collision still. So $ is wrapped in the argument for short-hand so that you can write $ instead of jQuery all around inside that function.
(function(){
}());
That is self-executing anonymous function again but with no arguments and runs/calls itself because of () at the end.
That patterns turns out to be extremely useful in some situations. For example, let's say you want to run a piece of code after 500 milli seconds each time, you would naturally go for setInterval.
setInterval(doStuff, 500);
But what if doStuff function takes more than 500 mill-seconds to do what it is doing? You would witness unexpected results but setInterval will keep on calling that function again and again at specified time irrespective of whether doStuff finished.
That is where that pattern comes in and you can do the same thing with setTimeout in combination with self-executing anonymous function and avoid bad setInterval like this:
(function foo(){
doStuff;
setTimeout(foo, 500);
})()
This code will also repeat itself again and again with one difference. setTimeout will never get triggered unless doStuff is finished. A much better approach than using bad setInterval.
You can test it here.
Note that you can also write self-executing anonymous function like this:
function(){
// some code
}();
Using extra braces around (like before function keyword) is simply coding convention and can be seen in Crackford's writings, jQuery and elsewhere.
$(function(){
});
That is short-hand syntax for ready handler:
$(document).ready(function(){
});
More Information:
How Self-Executing Anonymous Functions Work
I know that this question is old, but I stumbled upon it right now and so may other people. I just wanted to point out that, although Sarfraz's answer is great, it has to be said that no, writing a self-executing, anonymous function within braces is not a coding convention.
function(){
// some code
}();
Will not work and give out a SyntaxError because the function is being parsed as a FunctionDeclaration, and the function name is not optional in this case.
On the other hand, the Grouping Operator makes sure that the content is evaluated as a FunctionExpression.
See: Explain JavaScript's encapsulated anonymous function syntax
Taking the jQuery framework for example, if you run code like this:
$(document).ready(function init() { foo.bar(); });
The stack trace you get in Firebug will look like this:
init()
anonymous()
anonymous([function(), init(), function(), 4 more...], function(), Object name=args)
anonymous()
anonymous()
As you can see, it's not very readable, because you have to click on each function to find out what it is. The anonymous functions would also show up as (?)() in the profiler, and they can lead to the "cannot access optimized closure" bug. It seems to me that these are good reasons to avoid them. Then there's the fact that ECMAScript 5 will deprecate arguments.callee in its strict mode, which means it won't be possible to reference anonymous functions with it, making them a little less future-proof.
On the other hand, using named functions can lead to repetition, e.g.:
var Foo = {
bar: function bar() {}
}
function Foo() {}
Foo.prototype.bar = function bar() {}
Am I correct in thinking that this repetition is justified in light of the debugging convenience named functions provide, and that the prevalence of anonymous functions in good frameworks like jQuery is an oversight?
I agree there are certain downsides to using anonymous methods in JavaScript/EMCAScript. However, don't overlook how they should be used. For simple one liners that you want to pass to another function, they are often excellent.
I found the answer to my question in this very informative article. Firstly, it turns out that I was right about named functions being more desirable, but the solution is not as simple as adding identifiers to all anonymous functions. The main reason for this is JScript implementing function expressions in a very broken way.
Secondly, there is a distinction between function statements and expressions. An anonymous function is just a function expression with the identifier omitted, and adding an identifier (naming it) wouldn't make it a statement (except in JScript, which is why it's broken). This means that all of the other answers were off mark.
But for me anonymous functions are more readable in the source code, because I am sure they are only used there.
Anonymous functions are very convenient. A better fix to this problem, instead of naming the functions, would be if firebug told you on which line in which file the anonymous function was created.
init()
anonymous() // application.js, line 54
anonymous() // foo.js, line 2
And the stack trace is the only place where anonymous functions are a problem imo.