Invoke and define JavaScript function in same statement - javascript

Is this the correct way:
(function() {
// do something here
}());
Or this way:
(function() {
// do something here
})();

It's only a difference in style, both are "correct." I prefer the second and would venture that it's more popular, some prefer the first.
What you can't do is simply
function() {
// ...this example is wrong and won't work
}();
You need the parentheses in order to put the parser in the right mode that you're doing a function expression rather than a function declaration, but it doesn't matter whether the invoking parens at the end are within the main parens or outside them. You can try it with this live copy with the JavaScript engines in your favorite browsers...

Both work, although I use the second method (and see it used more often).

When you surround the function with parentheses, it becomes an expression (i.e. something that evaluates to a value). In other words, for the first example, its saying (evaluate me and execute me), and for the second is saying (evaluate everything in here)(and then execute me). I think the second is more intuitive because it separates what you are executing from the actual execution.

As others pointed out, you need something before "function" to make the parser treat this as an expression, but not necessary a parenthesis. For example, Objective C fans can also use these:
-function() { ... } ()
+function() { ... } ()

example :
function doSomething() { // The function code goes here }
You can click on
http://devlicio.us/blogs/sergio_pereira/archive/2009/02/09/javascript-5-ways-to-call-a-function.aspx
For More information :)

Related

Invoking a named function expression

Can I immediately call(invoke) a named function expression without a variable name like this?
var bookingMask = function (ac) {
....
}('.selectDates');
If you really mean "named" function expression, yes, you can do that:
(function bookingMask(ac) {
// ...
})('.selectDates');
Note the () wrapping it. Otherwise, the function keyword would lead the parser to assume that it was the beginning of a function declaration, which you can't directly invoke in that way.
You might want that if you want to use bookingMask inside the function (e.g., recursion).
Live Example:
(function bookingMask(ac) {
console.log("ac is: " + ac); // "ac is: .selectDates"
console.log(typeof bookingMask); // "function"
})('.selectDates');
If you meant bookingMask to be the result of the call, you can do that too:
var bookingMask = (function nameForTheFunctionHere(ac) {
// ...
})('.selectDates');
If you're doing that, since the parser is already expecting an expression as of the function keyword there, you don't need the wrapper (), this is fine:
var bookingMask = function nameForTheFunctionHere(ac) {
// ...
}('.selectDates');
...but I tend to keep them anyway, since it's really easy when reading the code to miss the (...) at the end.
You can also do it without a name (just remove bookingMask above), but you did specifically say "named", so... :-)
(If anyone's wondering why this answer has four downvotes, when I first posted an answer I missed the fact that the OP had mentioned a named function expression, not least because there isn't one in the question. A couple of people were kind enough to let me know so I could fix it. But people were initially voting on the incorrect answer.)
There are 2 different ways of declaring a function, you can either use function declaration or function expression. The 'expression' part means that it is either assigned to a value var func = function cat(){} or you use parentheses to tell the JavaScript engine to go get the value inside and evaluate it as an expression. So the name IFFE, immediately invoked function expression comes from first turning the function into an expression (function(){}) then calling it (function(){})().
So in your case, you do not want to evaluate the function 'assigning it to a variable' you want to create assign and run the function at once like so...
(function(ac) {
// code...
})('.selectDates');
If your feeling very adventurous you can also use other operators other than the parentheses to evaluate the IFFE such as;
+function IFFE(){
}()
-function IFFE(){
}()

Is there a way to evaluate a function defined as a string by using eval()?

I would like to store a function definition in a string, like for example:
var funcString = 'function(){ return 4+4 }'
Can I use eval() to evaluate the function?
Like for example:
var result = eval(funcString)
which will evaluate the string in funcString as a function and return 4+4 (8) in result.
edit: So from what you've told me I understood that I shouldn't use eval in that way, but for my case I don't think there is another way.
I would like to define a set of rules in a separate file and I want to instruct my Javascript Library to look into this file and search for the rules. The following is an example of a rule:
rule('logOut', (function() { return !JSLibrary.compareUserDetails })(), (function() { console.log("\n\nError: logged out user did not match\n\n\n") })())
I would like to evaluate both of the functions defined in the rules and I think that eval is the only way to do it. I don't know if there exist any other.
Fair warning, eval is "evil." I'll answer your question regardless, but you might want to rethink using eval.
In JavaScript, functions are values, just like 5, 'Stack Overflow' and document. In fact, what function myFunction(args) { body } does is create a function and throw it into a variable called myFunction*.
Say you wanted to take that function and put it into another variable. You can just say var otherVariable = myFunction. And if you want to call that function, you can just say otherVariable().
But say you want a function that isn't bound to a name, for instance if you're passing it to another function. You can use an anonymous function, defined as function(args) { body }. That's what's inside the string you're eval-ing. Anonymous functions are just like any other function, and you can call them as such. Actually, you can even call them right out of the result of eval by tacking on some parentheses at the end.
Unfortunately, it's not that easy though. You can't just write a line of code with an anonymous function definition and expect it to run: you will instead get an error complaining about it not being named. To fix this, throw some parenthesis around the definition to force it to be an expression instead of a statement.
Your final working code will look like this:
var funcString = '(function(){ return 4+4 })'
var result = eval(funcString)()
Sure, you should never use eval for this particular use, but I hope you learned a bit about JavaScript from this answer anyways.
* There's more to it than that, such as hoisting, but that doesn't really matter in this explanation.
Use of an immediately invoked function expression can call a function with eval.
document.body.innerHTML = eval('(function(){return 4+4;})()');
WARNING: do not ever do this: it's insecure, a performance-killer, harder to read/understand, etc

Immediate functions and different declarative syntaxes [duplicate]

There is a JSLint option, one of The Good Parts in fact, that "[requires] parens around immediate invocations," meaning that the construction
(function () {
// ...
})();
would instead need to be written as
(function () {
// ...
}());
My question is this -- can anyone explain why this second form might be considered better? Is it more resilient? Less error-prone? What advantage does it have over the first form?
Since asking this question, I have come to understand the importance of having a clear visual distinction between function values and the values of functions. Consider the case where the result of immediate invocation is the right-hand side of an assignment expression:
var someVar = (function () {
// ...
}());
Though the outermost parentheses are syntactically unnecessary, the opening parenthesis gives an up-front indication that the value being assigned is not the function itself but rather the result of the function being invoked.
This is similar to Crockford's advice regarding capitalization of constructor functions -- it is meant to serve as a visual cue to anyone looking at the source code.
From Douglass Crockford's style convention guide: (search for "invoked immediately")
When a function is to be invoked immediately, the entire invocation expression should be wrapped in parens so that it is clear that the value being produced is the result of the function and not the function itself.
So, basically, he feels it makes more clear the distinction between function values, and the values of functions. So, it's an stylistic matter, not really a substantive difference in the code itself.
updated reference, old PPT no longer exists
Immediately Called Anonymous Functions get wrapped it in parens because:
They are function expressions and leaving parens out would cause it to be interpreted as a function declaration which is a syntax error.
Function expressions cannot start with the word function.
When assigning the function expression to a variable, the function itself is not returned, the return value of the function is returned, hence the parens evaluate what's inside them and produce a value. when the function is executed, and the trailing parens ..}() cause the function to execute immediately.
Or, use:
void function () {
...
} ()

How should I declare my self-calling function?

I've seen self-calling functions in Javascript written like this:
(function () {
// foo!
})();
But I've also seen them written like this:
(function () {
// bar!
}());
Syntactically, they do exactly the same thing. My personal habit is the first format, actually, but is there any difference between the two that I should be aware of? Like browser kinks or whatever?
One very trivial thing, for example, is if the second format should work reliably, then it would mean that something like this should be possible as well:
function () {
// shut the front door! saved two characters right there!
}();
It hurts readability a good deal though.
First:
There is, like you assumed, absolutely no difference between the first two version of your self-invoking anonymous function. No browser klinks, quirks, just comes down to personal preference (Douglas Crockford calls the latter form "dog balls" by the way).
Second:
function() {
}()
will not work by design, since that statement creates a function statement/declaration. You need a function expression to immediately invoke itself. To create a function expression you can do multiple things. Putting the whole statement into parenthesis is one way, but you could also write
!function() {
}()
or
+function() {
}
All of these operators will make an expression.
The first two are identical, but if I remember correctly, one of them is preferred by jsLint (I think it’s the second).
The third raises a syntax error in most interpreters, but there are other variants:
!function() {
alert('I’m executing myself!');
}();
var noname = function() {
alert(noname); // undefined!
}();
​
You can replace the ! with a + or - ( None of them will make Crockford happy )
This is mostly a convention issue.
(function () {}()); <- one less stack frame before execution (maybe)
(function () {})(); <- executed outside the parenthesis, so one tiny little frame before execution, although I don't like this style, IMO it's visually disconnected.
function () {}(); <- this is just bad practice IMO, it's not immediately obvious that this is an IIFE which is mostly due to convention, but this also has the problem that if you forget a semi-colon before the expression it will, under some conditions silently assign variables the value undefined.
Example:
var x = 0,
y = 1,
z = 3,
function () {
alert("Z is now undefined, instead of throwing a syntax error.");
}();
As mentioned by Andre Meinhold, this is not in expression position.
Pragmatically speaking, JSLint will complain about the first and prefer the second format. Beyond that, it's really personal preference and consistency is key here.
The third format will result in a SyntaxError, so you can't use that. That's because your creating a function declaration, not a function expression. It's the function expression that you're calling when you use the immediate function pattern.
Crockford says to use (function () {...}()).
It's just a stylistic choice, but it's in the community's interest to agree upon a convention and (at the risk of starting a flame-war) why not use Crockford's?
Also, keep in mind that (function () { }()); adds potential confusion. Since in a long function, someone not paying attention might see two closing parentheses and only one being opened.

Is there any reason to wrap anonymous JavaScript functions in braces?

var a = function () {
return 'test';
}();
console.log(a);
Answer in First Case : test
var a = (function () {
return 'test';
})();
console.log(a);
Answer in Second Case : test
I am using the the first approach to create self-executing functions. However, I have seen the second approach as well. Is there any difference in the two approaches ? The result is obviously the same.
The first syntax is only valid if you assign the result of the function execution to a variable, If you just want to execute the function, this form would be a syntax error:
function(){
return 'test';
}();
The other form is still valid, though:
(function(){
return 'test';
})();
Therefore the second version is more flexible and can be used more consistently.
(The first form is not valid syntax to avoid ambiguities in the Javascript grammar.)
Yes, the first one sets the variable a as an anonymous variable, while the second one sets the variable a to the result of the function.
Edit: I read the first code wrong. The answer is no.
It is good practice (but not required) to wrap IIFEs (Immediately Invoked Function Expressions) in parenthesis for readability. If your function is long and the reader cannot see the end, the opening parenthesis calls the readers attention to the fact that there is something special about this function expression and forces them to look at the bottom to find out what it is.

Categories