Can we define a "function declaration" also as a "function statement"? - javascript

This question born considering the function declarations VS function expressions.
We clearly know that a function declaration have this form
function foo() {
var a = 3;
console.log( a );
}
while a function expression can have this form (appearing like what is known like Immediately invoked function expression)
(function foo() {
var a = 3;
console.log( a );
})()
Looking at the immediately invoked function expression I can just notice the first function (the one used in the function declaration) wrapped in parethesis.
Now, the point is: I know that the grouping operator (most commonly known as "the parethesis" () ) can only contain an expression. If this is true I can't say that the function declaration is also a function statement (because it would be like saying that I have wrapped in parenthesis a statement...).
So, can you give some help, I'm a little confused.
A function declaration is also a function statement? If yes, the function wrapped in parenthesis is a statement or what?
I must clarify that I'm not asking about the difference beetwen a function declaration and a function expression. If I mention them and their differences is just to describe my question that is: a "function declaration" is also a "function statement"?

While the syntax of a function expression is the same as a function declaration, they're not the same thing.
The scope of the name used in function declarations is different from named function expressions. When you write:
function foo() {
var a = 3;
console.log( a );
}
the scope of foo is the enclosing function (or the global environment if this is at top level).
When you write:
(function foo() {
var a = 3;
console.log( a );
})
the scope of foo is just the body of the function.
The parser determines whether it's a function expression or declaration based on the context. Since a statement can't be inside parentheses, putting parentheses around it forces it to be an expression.

In expression hoisting will not happened, but in function statement hoisting is occurred.
In function statement, You can write function definition anywhere in js file before or after function call. JIT compiler will hoisting at top of programming file.
For function expression, JIT compiler will not do as same as function statement, which reads where its occurred. If you try to access function before its defined it will show type error.
IIFE is pattern mostly used to avoid access variable outside function.
callMe(); // Function statement
function callMe(){
return console.log("I am function statement");
}
// callMe2(); // TypeError if you call before expression defined.
var callMe2 = function(){
return console.log("I am function expression");
};
callMe2(); //Function expression call
(function(){
return console.log("I am IIFE");
}());

Related

Immediately invoked function expression without using grouping operator

I'm trying to immediately invoke a function without using IIFE pattern (enclosing a function definition inside parentheses). Here I see two scenarios:
When a function declaration is invoked immediately: gives SyntaxError.
When a function expression is invoked immediately: executes successfully.
Example 1: gives SyntaxError
//gives `SyntaxError`
function() {
console.log('Inside the function');
}();
Example 2: Executes without any error
// Executes without any error
var x = function() {console.log('Inside the function')}(); // Inside the function
So, I have these doubts:
With this approach, why does it give an error for function declaration but not for function expression?
Is there a way we can immediately invoke a function declaration without using IIFE pattern?
In your code you don't have name for the function that's the reason for syntax error. Even if you would had name it would have thrown error.
function func(){
console.log('x')
}();
The reason is the function declaration doesn't return the values of the function however when you wrap function declaration inside () it forces it be a function expression which returns a value.
In the second example the function() {console.log('Inside the function')} is considered expression because it's on RightHandSide. So it executes without an error.
Is there a way we can immediately invoke a function declaration without using IIFE pattern
You can use + which will make function declaration an expression.
+function(){
console.log('done')
}()
If you don't want to use + and () you can use new keyword
new function(){
console.log('done')
}
Extra
A very interesting question is asked by #cat in the comments. I try to answer it.There are three cases
+function(){} //returns NaN
(+function(){return 5})() //VM140:1 Uncaught TypeError: (+(intermediate value)) is not a function
+function(){return 5}() //5
+function(){} returns NaN
+ acts as Unary Plus here which parses the value next to it to number. As Number(function(){}) returns NaN so it also returns NaN
(+function(){return 5;})() returns Error
Usually IIFE are created using (). () are used to make a function declaration an expression + is short way for that. Now +function(){} is already an expression which returns NaN. So calling NaN will return error. The code is same as
Number(function(){})()
+function(){return 5;}() returns 5
In the above line + is used to make a statement an expression. In the above example first function is called then + is used on it to convert it to number. So the above line is same as
Number(function(){return 5}())
In the proof of statement "+ runs on after the function is called" Consider the below snippet
console.log(typeof +function(){return '5'}());
So in the above snippet you can see the returned value is string '5' but is converted to number because of +
A function declaration, like
function foo() {
}
defines (and hoists) the variable name foo as a function in the current scope. A function declaration doesn't evaluate to a value; it just does something, a bit like an if does something (rather than evaluate to a value).
You can only invoke values which are functions, eg
<somevalue>()
where somevalue is a variable name that refers to a function.
Note that function declarations require function names, because otherwise there's no variable name to assign the function to - your original
//gives `SyntaxError`
function() {
console.log('Inside the function');
}();
throws not because of the () at the end, but because of the lack of a name.
You can put parentheses at the end of a function declaration, as long as there's something inside the parentheses - but these parentheses do not call the function, they evaluate to a value:
function x() {
console.log('Inside the function');
}(console.log('some expression inside parentheses'));
The interpreter sees these as two separate statements, like
function x() {
console.log('Inside the function');
}
// completely separate:
(console.log('some expression inside parentheses'));
The inside of the parentheses gets evaluated and then discarded, since it doesn't get assigned to anything.
(Empty parentheses are forbidden because they can't be evaluated to a value, similar to how const foo = () is forbidden)
The E in IIFE stands for expression, and without the wrapping parenthesis your function is not evaluated as an expression thus the syntax error.
creating an expression is a way of tricking the interpreter and be able to invoke the function immediatly
(function() {
console.log('Inside the function');
})();
In your example you have a function statement followed by the grouping operator, but it's syntactically incorrect for two reasons, first it doesn't have a name, and second because the grouping operator must have an expression inside it, infact if you add a valid one the error will disappear, still you won't obtain your desired result.
function foo() {
console.log('Inside the function');
}();
function foo() {
console.log('Inside the function');
}(1+2);
In order to invoke something, it has to be a function value, a declaration just declares a name, and does not evaluate to the function value itself, hence you cannot invoke it.
A declaration cannot be invoked for the above reason. You have to end up with an expression somehow, either through assignment or grouping (IIFE). So that is a no.
If you give us more context on why you would want to do that, maybe we can help with suggestions.
Not sure why you would want to do it, but:
Is there a way we can immediately invoke a function declaration without using IIFE pattern?
Well, if for function declaration you mean using the keyword function as in:
function name() { return this.name; }
As far as I know, no. You need the extra parentheses to tell the runtime not to assign the function to a name variable, if I understand this stuff right.
Now, what you actually can do is to use Function as in:
new Function('console.log("ey there")')();
Which will execute the console.log code. No need for IIFE here. But I don't see how this could be better than an IIFE.
you can call in either below ways -
~function(){console.log("hi")}()
!function(){console.log("hi")}()
+function(){console.log("hi")}()
-function(){console.log("hi")}()
(function(){console.log("hi")}());
var i = function(){console.log("hi")}();
true && function(){ console.log("hi") }();
0, function(){ console.log("hi") }();
new function(){ console.log("hi") }
new function(){ console.log("hi") }()

javascript auto execute anonymous function - parenthesis [duplicate]

I was reading some posts about closures and saw this everywhere, but there is no clear explanation how it works - everytime I was just told to use it...:
// Create a new anonymous function, to use as a wrapper
(function(){
// The variable that would, normally, be global
var msg = "Thanks for visiting!";
// Binding a new function to a global object
window.onunload = function(){
// Which uses the 'hidden' variable
alert( msg );
};
// Close off the anonymous function and execute it
})();
Ok I see that we will create new anonymous function and then execute it. So after that this simple code should work (and it does):
(function (msg){alert(msg)})('SO');
My question is what kind of magic happens here? I thought that when I wrote:
(function (msg){alert(msg)})
then a new unnamed function would be created like function ""(msg) ...
but then why doesn't this work?
(function (msg){alert(msg)});
('SO');
Why does it need to be in the same line?
Could you please point me some posts or give me an explanation?
Drop the semicolon after the function definition.
(function (msg){alert(msg)})
('SO');
Above should work.
DEMO Page: https://jsfiddle.net/e7ooeq6m/
I have discussed this kind of pattern in this post:
jQuery and $ questions
EDIT:
If you look at ECMA script specification, there are 3 ways you can define a function. (Page 98, Section 13 Function Definition)
1. Using Function constructor
var sum = new Function('a','b', 'return a + b;');
alert(sum(10, 20)); //alerts 30
2. Using Function declaration.
function sum(a, b)
{
return a + b;
}
alert(sum(10, 10)); //Alerts 20;
3. Function Expression
var sum = function(a, b) { return a + b; }
alert(sum(5, 5)); // alerts 10
So you may ask, what's the difference between declaration and expression?
From ECMA Script specification:
FunctionDeclaration :
function Identifier ( FormalParameterListopt ){ FunctionBody
}
FunctionExpression :
function Identifieropt ( FormalParameterListopt ){ FunctionBody
}
If you notice, 'identifier' is optional for function expression. And when you don't give an identifier, you create an anonymous function. It doesn't mean that you can't specify an identifier.
This means following is valid.
var sum = function mySum(a, b) { return a + b; }
Important point to note is that you can use 'mySum' only inside the mySum function body, not outside. See following example:
var test1 = function test2() { alert(typeof test2); }
alert(typeof(test2)); //alerts 'undefined', surprise!
test1(); //alerts 'function' because test2 is a function.
Live Demo
Compare this to
function test1() { alert(typeof test1) };
alert(typeof test1); //alerts 'function'
test1(); //alerts 'function'
Armed with this knowledge, let's try to analyze your code.
When you have code like,
function(msg) { alert(msg); }
You created a function expression. And you can execute this function expression by wrapping it inside parenthesis.
(function(msg) { alert(msg); })('SO'); //alerts SO.
It's called a self-invoked function.
What you are doing when you call (function(){}) is returning a function object. When you append () to it, it is invoked and anything in the body is executed. The ; denotes the end of the statement, that's why the 2nd invocation fails.
One thing I found confusing is that the "()" are grouping operators.
Here is your basic declared function.
Ex. 1:
var message = 'SO';
function foo(msg) {
alert(msg);
}
foo(message);
Functions are objects, and can be grouped. So let's throw parens around the function.
Ex. 2:
var message = 'SO';
function foo(msg) { //declares foo
alert(msg);
}
(foo)(message); // calls foo
Now instead of declaring and right-away calling the same function, we can use basic substitution to declare it as we call it.
Ex. 3.
var message = 'SO';
(function foo(msg) {
alert(msg);
})(message); // declares & calls foo
Finally, we don't have a need for that extra foo because we're not using the name to call it! Functions can be anonymous.
Ex. 4.
var message = 'SO';
(function (msg) { // remove unnecessary reference to foo
alert(msg);
})(message);
To answer your question, refer back to Example 2. Your first line declares some nameless function and groups it, but does not call it. The second line groups a string. Both do nothing. (Vincent's first example.)
(function (msg){alert(msg)});
('SO'); // nothing.
(foo);
(msg); //Still nothing.
But
(foo)
(msg); //works
An anonymous function is not a function with the name "". It is simply a function without a name.
Like any other value in JavaScript, a function does not need a name to be created. Though it is far more useful to actually bind it to a name just like any other value.
But like any other value, you sometimes want to use it without binding it to a name. That's the self-invoking pattern.
Here is a function and a number, not bound, they do nothing and can never be used:
function(){ alert("plop"); }
2;
So we have to store them in a variable to be able to use them, just like any other value:
var f = function(){ alert("plop"); }
var n = 2;
You can also use syntatic sugar to bind the function to a variable:
function f(){ alert("plop"); }
var n = 2;
But if naming them is not required and would lead to more confusion and less readability, you could just use them right away.
(function(){ alert("plop"); })(); // will display "plop"
alert(2 + 3); // will display 5
Here, my function and my numbers are not bound to a variable, but they can still be used.
Said like this, it looks like self-invoking function have no real value. But you have to keep in mind that JavaScript scope delimiter is the function and not the block ({}).
So a self-invoking function actually has the same meaning as a C++, C# or Java block. Which means that variable created inside will not "leak" outside the scope. This is very useful in JavaScript in order not to pollute the global scope.
It's just how JavaScript works. You can declare a named function:
function foo(msg){
alert(msg);
}
And call it:
foo("Hi!");
Or, you can declare an anonymous function:
var foo = function (msg) {
alert(msg);
}
And call that:
foo("Hi!");
Or, you can just never bind the function to a name:
(function(msg){
alert(msg);
})("Hi!");
Functions can also return functions:
function make_foo() {
return function(msg){ alert(msg) };
}
(make_foo())("Hi!");
It's worth nothing that any variables defined with "var" in the body of make_foo will be closed over by each function returned by make_foo. This is a closure, and it means that the any change made to the value by one function will be visible by another.
This lets you encapsulate information, if you desire:
function make_greeter(msg){
return function() { alert(msg) };
}
var hello = make_greeter("Hello!");
hello();
It's just how nearly every programming language but Java works.
The code you show,
(function (msg){alert(msg)});
('SO');
consist of two statements. The first is an expression which yields a function object (which will then be garbage collected because it is not saved). The second is an expression which yields a string. To apply the function to the string, you either need to pass the string as an argument to the function when it is created (which you also show above), or you will need to actually store the function in a variable, so that you can apply it at a later time, at your leisure. Like so:
var f = (function (msg){alert(msg)});
f('SO');
Note that by storing an anonymous function (a lambda function) in a variable, your are effectively giving it a name. Hence you may just as well define a regular function:
function f(msg) {alert(msg)};
f('SO');
In summary of the previous comments:
function() {
alert("hello");
}();
when not assigned to a variable, yields a syntax error. The code is parsed as a function statement (or definition), which renders the closing parentheses syntactically incorrect. Adding parentheses around the function portion tells the interpreter (and programmer) that this is a function expression (or invocation), as in
(function() {
alert("hello");
})();
This is a self-invoking function, meaning it is created anonymously and runs immediately because the invocation happens in the same line where it is declared. This self-invoking function is indicated with the familiar syntax to call a no-argument function, plus added parentheses around the name of the function: (myFunction)();.
There is a good SO discussion JavaScript function syntax.
My understanding of the asker's question is such that:
How does this magic work:
(function(){}) ('input') // Used in his example
I may be wrong. However, the usual practice that people are familiar with is:
(function(){}('input') )
The reason is such that JavaScript parentheses AKA (), can't contain statements and when the parser encounters the function keyword, it knows to parse it as a function expression and not a function declaration.
Source: blog post Immediately-Invoked Function Expression (IIFE)
examples without brackets:
void function (msg) { alert(msg); }
('SO');
(this is the only real use of void, afaik)
or
var a = function (msg) { alert(msg); }
('SO');
or
!function (msg) { alert(msg); }
('SO');
work as well. the void is causing the expression to evaluate, as well as the assignment and the bang. the last one works with ~, +, -, delete, typeof, some of the unary operators (void is one as well). not working are of couse ++, -- because of the requirement of a variable.
the line break is not necessary.
This answer is not strictly related to the question, but you might be interested to find out that this kind of syntax feature is not particular to functions. For example, we can always do something like this:
alert(
{foo: "I am foo", bar: "I am bar"}.foo
); // alerts "I am foo"
Related to functions. As they are objects, which inherit from Function.prototype, we can do things like:
Function.prototype.foo = function () {
return function () {
alert("foo");
};
};
var bar = (function () {}).foo();
bar(); // alerts foo
And you know, we don't even have to surround functions with parenthesis in order to execute them. Anyway, as long as we try to assign the result to a variable.
var x = function () {} (); // this function is executed but does nothing
function () {} (); // syntax error
One other thing you may do with functions, as soon as you declare them, is to invoke the new operator over them and obtain an object. The following are equivalent:
var obj = new function () {
this.foo = "bar";
};
var obj = {
foo : "bar"
};
There is one more property JavaScript function has. If you want to call same anonymous function recursively.
(function forInternalOnly(){
//you can use forInternalOnly to call this anonymous function
/// forInternalOnly can be used inside function only, like
var result = forInternalOnly();
})();
//this will not work
forInternalOnly();// no such a method exist
It is a self-executing anonymous function. The first set of brackets contain the expressions to be executed, and the second set of brackets executes those expressions.
(function () {
return ( 10 + 20 );
})();
Peter Michaux discusses the difference in An Important Pair of Parentheses.
It is a useful construct when trying to hide variables from the parent namespace. All the code within the function is contained in the private scope of the function, meaning it can't be accessed at all from outside the function, making it truly private.
See:
Closure (computer science)
JavaScript Namespacing
Important Pair of Javascript Parentheses
Another point of view
First, you can declare an anonymous function:
var foo = function(msg){
alert(msg);
}
Then you call it:
foo ('Few');
Because foo = function(msg){alert(msg);} so you can replace foo as:
function(msg){
alert(msg);
} ('Few');
But you should wrap your entire anonymous function inside pair of braces to avoid syntax error of declaring function when parsing. Then we have,
(function(msg){
alert(msg);
}) ('Few');
By this way, It's easy understand for me.
When you did:
(function (msg){alert(msg)});
('SO');
You ended the function before ('SO') because of the semicolon. If you just write:
(function (msg){alert(msg)})
('SO');
It will work.
Working example: http://jsfiddle.net/oliverni/dbVjg/
The simple reason why it doesn't work is not because of the ; indicating the end of the anonymous function. It is because without the () on the end of a function call, it is not a function call. That is,
function help() {return true;}
If you call result = help(); this is a call to a function and will return true.
If you call result = help; this is not a call. It is an assignment where help is treated like data to be assigned to result.
What you did was declaring/instantiating an anonymous function by adding the semicolon,
(function (msg) { /* Code here */ });
and then tried to call it in another statement by using just parentheses... Obviously because the function has no name, but this will not work:
('SO');
The interpreter sees the parentheses on the second line as a new instruction/statement, and thus it does not work, even if you did it like this:
(function (msg){/*code here*/});('SO');
It still doesn't work, but it works when you remove the semicolon because the interpreter ignores white spaces and carriages and sees the complete code as one statement.
(function (msg){/*code here*/}) // This space is ignored by the interpreter
('SO');
Conclusion: a function call is not a function call without the () on the end unless under specific conditions such as being invoked by another function, that is, onload='help' would execute the help function even though the parentheses were not included. I believe setTimeout and setInterval also allow this type of function call too, and I also believe that the interpreter adds the parentheses behind the scenes anyhow which brings us back to "a function call is not a function call without the parentheses".
(function (msg){alert(msg)})
('SO');
This is a common method of using an anonymous function as a closure which many JavaScript frameworks use.
This function called is automatically when the code is compiled.
If placing ; at the first line, the compiler treated it as two different lines. So you can't get the same results as above.
This can also be written as:
(function (msg){alert(msg)}('SO'));
For more details, look into JavaScript/Anonymous Functions.
The IIFE simply compartmentalizes the function and hides the msg variable so as to not "pollute" the global namespace. In reality, just keep it simple and do like below unless you are building a billion dollar website.
var msg = "later dude";
window.onunload = function(msg){
alert( msg );
};
You could namespace your msg property using a Revealing Module Pattern like:
var myScript = (function() {
var pub = {};
//myscript.msg
pub.msg = "later dude";
window.onunload = function(msg) {
alert(msg);
};
//API
return pub;
}());
Anonymous functions are functions that are dynamically declared at
runtime. They’re called anonymous functions because they aren’t
given a name in the same way as normal functions.
Anonymous functions are declared using the function operator instead
of the function declaration. You can use the function operator to
create a new function wherever it’s valid to put an expression. For
example, you could declare a new function as a parameter to a
function call or to assign a property of another object.
Here’s a typical example of a named function:
function flyToTheMoon() {
alert("Zoom! Zoom! Zoom!");
}
flyToTheMoon();
Here’s the same example created as an anonymous function:
var flyToTheMoon = function() {
alert("Zoom! Zoom! Zoom!");
}
flyToTheMoon();
For details please read http://helephant.com/2008/08/23/javascript-anonymous-functions/
Anonymous functions are meant to be one-shot deal where you define a function on the fly so that it generates an output from you from an input that you are providing. Except that you did not provide the input. Instead, you wrote something on the second line ('SO'); - an independent statement that has nothing to do with the function. What did you expect? :)

Any difference between f() and (f())?

Any difference between
var myfunc = (function () { return function () { ... } }());
and
var myfunc = function () { return function () { ... } }();
Is it just a matter of style or is there more to the surrounding () in the first form?
Nope. Or at least not in your example.
The outer parens only matter when the function keyword would be the first token in a statement.
// cool
var foo = function(){}();
var foo = (function(){}());
// also cool
(function(){}());
// not cool, syntax error
// parsed as function statement, expects function name which is missing
function(){}();
// also not cool, syntax error
// declares a function, but can't be executed immediately
function foo(){}();
When function is the first token in a statement, it's a function declaration (think named function), which behaves slightly differently than function in all other contexts. That leading paren forces the parses to treat it like a function expression (think anonymous function) instead, which allows immediate execution.
See: What is the difference between a function expression vs declaration in JavaScript?
If you start the line or statement with something else, like variable declaration, it technically doesn't matter at all.
No difference, though Crockford advises the use of the former, to ascertain that it's being treated as a function expression.
For more info, read these:
Immediately-Invoked Function Expression (IIFE)
Named function expressions demystified
There's no technical difference, It's just an idiomatic style used for readability to signal at the start that it's a self-invoking function.
no difference, it is just a matter of style. Both are executed functions and they return whatever they return in the variable and they are returning a function. check this out
the purpose is to avoid the global scope, adding the var myfunc = in front of (function (){ return function(){}}()); essentially defeats the purpose
compare the two
(function(){...do something...}());
this function is ran in a local scope, which is inside the parentheses.
var myfunc = function(){};
this function is ran on the global scope.
why not this way, because you can get your self into naming conflicts with other methods and var as well as plugin's named var and it can hinder your applications performance with the var being saved on the global scope.
I perfer
(function() {})();

JavaScript: What is an anonymous function? [duplicate]

I was reading some posts about closures and saw this everywhere, but there is no clear explanation how it works - everytime I was just told to use it...:
// Create a new anonymous function, to use as a wrapper
(function(){
// The variable that would, normally, be global
var msg = "Thanks for visiting!";
// Binding a new function to a global object
window.onunload = function(){
// Which uses the 'hidden' variable
alert( msg );
};
// Close off the anonymous function and execute it
})();
Ok I see that we will create new anonymous function and then execute it. So after that this simple code should work (and it does):
(function (msg){alert(msg)})('SO');
My question is what kind of magic happens here? I thought that when I wrote:
(function (msg){alert(msg)})
then a new unnamed function would be created like function ""(msg) ...
but then why doesn't this work?
(function (msg){alert(msg)});
('SO');
Why does it need to be in the same line?
Could you please point me some posts or give me an explanation?
Drop the semicolon after the function definition.
(function (msg){alert(msg)})
('SO');
Above should work.
DEMO Page: https://jsfiddle.net/e7ooeq6m/
I have discussed this kind of pattern in this post:
jQuery and $ questions
EDIT:
If you look at ECMA script specification, there are 3 ways you can define a function. (Page 98, Section 13 Function Definition)
1. Using Function constructor
var sum = new Function('a','b', 'return a + b;');
alert(sum(10, 20)); //alerts 30
2. Using Function declaration.
function sum(a, b)
{
return a + b;
}
alert(sum(10, 10)); //Alerts 20;
3. Function Expression
var sum = function(a, b) { return a + b; }
alert(sum(5, 5)); // alerts 10
So you may ask, what's the difference between declaration and expression?
From ECMA Script specification:
FunctionDeclaration :
function Identifier ( FormalParameterListopt ){ FunctionBody
}
FunctionExpression :
function Identifieropt ( FormalParameterListopt ){ FunctionBody
}
If you notice, 'identifier' is optional for function expression. And when you don't give an identifier, you create an anonymous function. It doesn't mean that you can't specify an identifier.
This means following is valid.
var sum = function mySum(a, b) { return a + b; }
Important point to note is that you can use 'mySum' only inside the mySum function body, not outside. See following example:
var test1 = function test2() { alert(typeof test2); }
alert(typeof(test2)); //alerts 'undefined', surprise!
test1(); //alerts 'function' because test2 is a function.
Live Demo
Compare this to
function test1() { alert(typeof test1) };
alert(typeof test1); //alerts 'function'
test1(); //alerts 'function'
Armed with this knowledge, let's try to analyze your code.
When you have code like,
function(msg) { alert(msg); }
You created a function expression. And you can execute this function expression by wrapping it inside parenthesis.
(function(msg) { alert(msg); })('SO'); //alerts SO.
It's called a self-invoked function.
What you are doing when you call (function(){}) is returning a function object. When you append () to it, it is invoked and anything in the body is executed. The ; denotes the end of the statement, that's why the 2nd invocation fails.
One thing I found confusing is that the "()" are grouping operators.
Here is your basic declared function.
Ex. 1:
var message = 'SO';
function foo(msg) {
alert(msg);
}
foo(message);
Functions are objects, and can be grouped. So let's throw parens around the function.
Ex. 2:
var message = 'SO';
function foo(msg) { //declares foo
alert(msg);
}
(foo)(message); // calls foo
Now instead of declaring and right-away calling the same function, we can use basic substitution to declare it as we call it.
Ex. 3.
var message = 'SO';
(function foo(msg) {
alert(msg);
})(message); // declares & calls foo
Finally, we don't have a need for that extra foo because we're not using the name to call it! Functions can be anonymous.
Ex. 4.
var message = 'SO';
(function (msg) { // remove unnecessary reference to foo
alert(msg);
})(message);
To answer your question, refer back to Example 2. Your first line declares some nameless function and groups it, but does not call it. The second line groups a string. Both do nothing. (Vincent's first example.)
(function (msg){alert(msg)});
('SO'); // nothing.
(foo);
(msg); //Still nothing.
But
(foo)
(msg); //works
An anonymous function is not a function with the name "". It is simply a function without a name.
Like any other value in JavaScript, a function does not need a name to be created. Though it is far more useful to actually bind it to a name just like any other value.
But like any other value, you sometimes want to use it without binding it to a name. That's the self-invoking pattern.
Here is a function and a number, not bound, they do nothing and can never be used:
function(){ alert("plop"); }
2;
So we have to store them in a variable to be able to use them, just like any other value:
var f = function(){ alert("plop"); }
var n = 2;
You can also use syntatic sugar to bind the function to a variable:
function f(){ alert("plop"); }
var n = 2;
But if naming them is not required and would lead to more confusion and less readability, you could just use them right away.
(function(){ alert("plop"); })(); // will display "plop"
alert(2 + 3); // will display 5
Here, my function and my numbers are not bound to a variable, but they can still be used.
Said like this, it looks like self-invoking function have no real value. But you have to keep in mind that JavaScript scope delimiter is the function and not the block ({}).
So a self-invoking function actually has the same meaning as a C++, C# or Java block. Which means that variable created inside will not "leak" outside the scope. This is very useful in JavaScript in order not to pollute the global scope.
It's just how JavaScript works. You can declare a named function:
function foo(msg){
alert(msg);
}
And call it:
foo("Hi!");
Or, you can declare an anonymous function:
var foo = function (msg) {
alert(msg);
}
And call that:
foo("Hi!");
Or, you can just never bind the function to a name:
(function(msg){
alert(msg);
})("Hi!");
Functions can also return functions:
function make_foo() {
return function(msg){ alert(msg) };
}
(make_foo())("Hi!");
It's worth nothing that any variables defined with "var" in the body of make_foo will be closed over by each function returned by make_foo. This is a closure, and it means that the any change made to the value by one function will be visible by another.
This lets you encapsulate information, if you desire:
function make_greeter(msg){
return function() { alert(msg) };
}
var hello = make_greeter("Hello!");
hello();
It's just how nearly every programming language but Java works.
The code you show,
(function (msg){alert(msg)});
('SO');
consist of two statements. The first is an expression which yields a function object (which will then be garbage collected because it is not saved). The second is an expression which yields a string. To apply the function to the string, you either need to pass the string as an argument to the function when it is created (which you also show above), or you will need to actually store the function in a variable, so that you can apply it at a later time, at your leisure. Like so:
var f = (function (msg){alert(msg)});
f('SO');
Note that by storing an anonymous function (a lambda function) in a variable, your are effectively giving it a name. Hence you may just as well define a regular function:
function f(msg) {alert(msg)};
f('SO');
In summary of the previous comments:
function() {
alert("hello");
}();
when not assigned to a variable, yields a syntax error. The code is parsed as a function statement (or definition), which renders the closing parentheses syntactically incorrect. Adding parentheses around the function portion tells the interpreter (and programmer) that this is a function expression (or invocation), as in
(function() {
alert("hello");
})();
This is a self-invoking function, meaning it is created anonymously and runs immediately because the invocation happens in the same line where it is declared. This self-invoking function is indicated with the familiar syntax to call a no-argument function, plus added parentheses around the name of the function: (myFunction)();.
There is a good SO discussion JavaScript function syntax.
My understanding of the asker's question is such that:
How does this magic work:
(function(){}) ('input') // Used in his example
I may be wrong. However, the usual practice that people are familiar with is:
(function(){}('input') )
The reason is such that JavaScript parentheses AKA (), can't contain statements and when the parser encounters the function keyword, it knows to parse it as a function expression and not a function declaration.
Source: blog post Immediately-Invoked Function Expression (IIFE)
examples without brackets:
void function (msg) { alert(msg); }
('SO');
(this is the only real use of void, afaik)
or
var a = function (msg) { alert(msg); }
('SO');
or
!function (msg) { alert(msg); }
('SO');
work as well. the void is causing the expression to evaluate, as well as the assignment and the bang. the last one works with ~, +, -, delete, typeof, some of the unary operators (void is one as well). not working are of couse ++, -- because of the requirement of a variable.
the line break is not necessary.
This answer is not strictly related to the question, but you might be interested to find out that this kind of syntax feature is not particular to functions. For example, we can always do something like this:
alert(
{foo: "I am foo", bar: "I am bar"}.foo
); // alerts "I am foo"
Related to functions. As they are objects, which inherit from Function.prototype, we can do things like:
Function.prototype.foo = function () {
return function () {
alert("foo");
};
};
var bar = (function () {}).foo();
bar(); // alerts foo
And you know, we don't even have to surround functions with parenthesis in order to execute them. Anyway, as long as we try to assign the result to a variable.
var x = function () {} (); // this function is executed but does nothing
function () {} (); // syntax error
One other thing you may do with functions, as soon as you declare them, is to invoke the new operator over them and obtain an object. The following are equivalent:
var obj = new function () {
this.foo = "bar";
};
var obj = {
foo : "bar"
};
There is one more property JavaScript function has. If you want to call same anonymous function recursively.
(function forInternalOnly(){
//you can use forInternalOnly to call this anonymous function
/// forInternalOnly can be used inside function only, like
var result = forInternalOnly();
})();
//this will not work
forInternalOnly();// no such a method exist
It is a self-executing anonymous function. The first set of brackets contain the expressions to be executed, and the second set of brackets executes those expressions.
(function () {
return ( 10 + 20 );
})();
Peter Michaux discusses the difference in An Important Pair of Parentheses.
It is a useful construct when trying to hide variables from the parent namespace. All the code within the function is contained in the private scope of the function, meaning it can't be accessed at all from outside the function, making it truly private.
See:
Closure (computer science)
JavaScript Namespacing
Important Pair of Javascript Parentheses
Another point of view
First, you can declare an anonymous function:
var foo = function(msg){
alert(msg);
}
Then you call it:
foo ('Few');
Because foo = function(msg){alert(msg);} so you can replace foo as:
function(msg){
alert(msg);
} ('Few');
But you should wrap your entire anonymous function inside pair of braces to avoid syntax error of declaring function when parsing. Then we have,
(function(msg){
alert(msg);
}) ('Few');
By this way, It's easy understand for me.
When you did:
(function (msg){alert(msg)});
('SO');
You ended the function before ('SO') because of the semicolon. If you just write:
(function (msg){alert(msg)})
('SO');
It will work.
Working example: http://jsfiddle.net/oliverni/dbVjg/
The simple reason why it doesn't work is not because of the ; indicating the end of the anonymous function. It is because without the () on the end of a function call, it is not a function call. That is,
function help() {return true;}
If you call result = help(); this is a call to a function and will return true.
If you call result = help; this is not a call. It is an assignment where help is treated like data to be assigned to result.
What you did was declaring/instantiating an anonymous function by adding the semicolon,
(function (msg) { /* Code here */ });
and then tried to call it in another statement by using just parentheses... Obviously because the function has no name, but this will not work:
('SO');
The interpreter sees the parentheses on the second line as a new instruction/statement, and thus it does not work, even if you did it like this:
(function (msg){/*code here*/});('SO');
It still doesn't work, but it works when you remove the semicolon because the interpreter ignores white spaces and carriages and sees the complete code as one statement.
(function (msg){/*code here*/}) // This space is ignored by the interpreter
('SO');
Conclusion: a function call is not a function call without the () on the end unless under specific conditions such as being invoked by another function, that is, onload='help' would execute the help function even though the parentheses were not included. I believe setTimeout and setInterval also allow this type of function call too, and I also believe that the interpreter adds the parentheses behind the scenes anyhow which brings us back to "a function call is not a function call without the parentheses".
(function (msg){alert(msg)})
('SO');
This is a common method of using an anonymous function as a closure which many JavaScript frameworks use.
This function called is automatically when the code is compiled.
If placing ; at the first line, the compiler treated it as two different lines. So you can't get the same results as above.
This can also be written as:
(function (msg){alert(msg)}('SO'));
For more details, look into JavaScript/Anonymous Functions.
The IIFE simply compartmentalizes the function and hides the msg variable so as to not "pollute" the global namespace. In reality, just keep it simple and do like below unless you are building a billion dollar website.
var msg = "later dude";
window.onunload = function(msg){
alert( msg );
};
You could namespace your msg property using a Revealing Module Pattern like:
var myScript = (function() {
var pub = {};
//myscript.msg
pub.msg = "later dude";
window.onunload = function(msg) {
alert(msg);
};
//API
return pub;
}());
Anonymous functions are functions that are dynamically declared at
runtime. They’re called anonymous functions because they aren’t
given a name in the same way as normal functions.
Anonymous functions are declared using the function operator instead
of the function declaration. You can use the function operator to
create a new function wherever it’s valid to put an expression. For
example, you could declare a new function as a parameter to a
function call or to assign a property of another object.
Here’s a typical example of a named function:
function flyToTheMoon() {
alert("Zoom! Zoom! Zoom!");
}
flyToTheMoon();
Here’s the same example created as an anonymous function:
var flyToTheMoon = function() {
alert("Zoom! Zoom! Zoom!");
}
flyToTheMoon();
For details please read http://helephant.com/2008/08/23/javascript-anonymous-functions/
Anonymous functions are meant to be one-shot deal where you define a function on the fly so that it generates an output from you from an input that you are providing. Except that you did not provide the input. Instead, you wrote something on the second line ('SO'); - an independent statement that has nothing to do with the function. What did you expect? :)

Is this an anonymous function?

In the first snippet below, based on my understanding I am creating a function and assigning it to a variable. But does that mean the function will take that name of the variable ?
var aFunc = function(){};
I know this is named function.
function bFunc(){};
So, first of all we have to clarify the main difference between the two functions you wrote.
This one:
var aFunc = function(){};
is a function expression. Where this one:
function bFunc(){};
is a function declaration.
In a function expression you're using the function operator to defines a function inside an expression.
When you declare a function you're using the function statement.
At the beginning it can be confusing because they're really similar, however function declaration and function expression behaves differently. First of all, you can't declare a function that is anonymous: if you're using a function statement, the name is mandatory.
So only functions defined with the function operator can be anonymous:
var aFunc = function(){};
That's an anonymous function. In some browsers you can actually print the function's name and see by yourself:
console.log(aFunc.name);
(Notice that this is not standard yet, but there is a proposal)
But it doesn't means that functions declared with the function operator have to be anonymous. For instance:
var aFunc = function myFunction() {};
It's a named function. However, that's still different from having a function declaration like that:
function myFunction() {};
var aFunc = myFunction;
Why? Because in case of function expression, you don't declare a myFunction function in the scope:
var aFunc = function myFunction() {};
console.log(typeof myFunction) // undefined, unless some bugs
So what's the point to give a name to a function expression? The answer is: to have access from that function from the function's body itself, without pollute the scope. Imaging for instance you want to add an event listener to a DOM node, but execute the listener only once:
document.body.addEventListener("click", function onclick() {
// do something
document.body.removeEventListener("click", onclick, false);
}, false);
So you don't pollute the scope with a lot of functions that you use only for purpose like that ones, and you can still have access to the function from the function's body. That's especially useful in ES5 where arguments.callee is deprecated, and for recursion.
Another difference between function expression is that you can invoke them immediately, but you can't do that for function declaration. So, for instance:
function() {
console.log('foo');
}();
Will throw an exception, because the engine can't understand if it's a function declaration or a function expression. But if you force the engine to look at it as an expression:
!function() {
console.log('foo');
}();
// or
(function(){
console.log('foo');
}());
// etc, there are a lot of ways
Here we are: JS understand is an expression, therefore threats the function as an operator and not as a statement. And you obtain the IIFE (Immediately-Invoked Function Expression), that are useful in a lot of scenarios, specially where you want to isolate code.
So, back to you question, why the name of this function:
var aFunc = function(){};
is not aFunc?
Because, it's an expression. So the value knows nothing about the assignment on the left. It's like having:
var aFunc = -3;
Where the - is the Unary Negation operation and the 3 is the value: they knows nothing about aFunc, right? It's exactly the same with function expression, where function is the operator, and (){} is the value.
No.
In the first example you are creating an anonymous function and then assigning it to "aFunc"
In the second example you declare a function and call it bFunc.
The most notable difference between the two is that you can't call "aFunc" until after the line where you assign it.
No, the function will not "take the name of the variable". The variable will hold a reference to an anonymous function. The function itself is still anonymous.
Note that this makes little difference in the end though, this function reference can be treated exactly the same as any regular named function once it's assigned. In fact, it makes so little difference, a named function can be treated like a variable holding a function reference too:
function foo() { }
foo();
foo = 'bar';
alert(foo); // bar
The term "anonymous function" is jargon, so likely what it means will change over time. There is no specification that states what it is, so it can be whatever you want it to be. And whatever you decide will likely be disputed by someone else. Jargon is like that (look up the word "trunking", a common jargon term in telephony).
Strictly, there are function declarations where the name is mandatory, e.g.
function foo() {
...
}
and function expressions where the name is optional. If the name is missing, e.g.:
var x = function () {
...
};
then that, to me, is an anonymous function. If it has a name, e.g.
var x = function foo() {
...
};
then it's a named function expression (and not an anonymous function). From my perspective, any function expression without an optional name is an anonymous function. There are many uses for function expressions, e.g.
// assignment to a variable
var x = function() {...}
// pass as a parameter
foo(function(){...})
// immediately executed and pass the result
foo( (function(){...}()) )
and so on. So in the OP, the right hand side of the assignment is a function expression with no name so to me, that's an anonymous function. The fact that it's then assigned to an identifier doesn't suddenly make it a named function expression.
Others may differ of course.
Incidentally, the results of:
function foo(){}
and
var foo = function(){};
are practically indistinguishable, the main difference is when the functions are created.
No it is not. The right hand side of your first statement is a Function Expression. It is anonymous as long as you don't assign it to a variable.
After you have assigned it, you can use it as a declared function.
See more details about function declarations in this question

Categories

Resources