!Function(){ }() VS (Function(){ })()

!function(){ }() vs (function(){ })()

  • One less character when minified.
  • The ! should handle where other JavaScript code is concatenated before this and doesn't have a trailing semi-colon.

There is not a huge difference. I would use whatever you were more comfortable with. You should probably toss something at the start of your example to avoid...

base.js

var lol = function() {
alert(arguments[0]);
}

im-concat-to-base.js

(function() {
// Irrelevant.
})();

jsFiddle.

Toss in a leading ; and she works...

jsFiddle.

...or a ! like the Twitter Bootstrap...

jsFiddle.

whats the difference between function foo(){} and foo = function(){}?

No, they're not the same, although they do both result in a function you can call via the symbol foo. One is a function declaration, the other is a function expression. They are evaluated at different times, have different effects on the scope in which they're defined, and are legal in different places.

Quoting my answer to this other question here (edited a bit for relevance), in case the other question were ever removed for some reason (and to save people following the link):


JavaScript has two different but related things: Function declarations, and function expressions. There are marked differences between them:

This is a function declaration:

function foo() {
// ...
}

Function declarations are evaluated upon entry into the enclosing scope, before any step-by-step code is executed. The function's name (foo) is added to the enclosing scope (technically, the variable object for the execution context the function is defined in).

This is a function expression (specifically, an anonymous one, like your quoted code):

var foo = function() {
// ...
};

Function expressions are evaluated as part of the step-by-step code, at the point where they appear (just like any other expression). That one creates a function with no name, which it assigns to the foo variable.

Function expressions can also be named rather than anonymous. A named one looks like this:

var x = function foo() {  // Valid, but don't do it; see details below 
// ...
};

A named function expression should be valid, according to the spec. It should create a function with the name foo, but not put foo in the enclosing scope, and then assign that function to the x variable (all of this happening when the expression is encountered in the step-by-step code). When I say it shouldn't put foo in the enclosing scope, I mean exactly that:

var x = function foo() {
alert(typeof foo); // alerts "function" (in compliant implementations)
};
alert(typeof foo); // alerts "undefined" (in compliant implementations)

Note how that's different from the way function declarations work (where the function's name is added to the enclosing scope).

Named function expressions work on compliant implementations, but there used to be several bugs in implementations in the wild, most especially Internet Explorer 8 and earlier (and some early versions of Safari). IE8 processes a named function expresssion twice: First as a function declaration (upon entry into the execution context), and then later as a function expression, generating two distinct functions in the process. (Really.)

More here: Double take and here: Named function expressions demystified


NOTE: The below was written in 2011. In 2015, function declarations in control blocks were added to the language as part of ECMAScript 2015. Their semantics vary depending on whether you're in strict or loose mode, and in loose mode if the environment is a web browser. And of course, on whether the environment you're using has correct support for the ES2015 definition for them. (To my surprise, as of this writing in July 2017, Babel doesn't correctly transpile them, either.) Consequently, you can only reliably use function declarations within control-flow structures in specific situations, so it's still probably best, for now, to use function expressions instead.


And finally, another difference between them is where they're legal. A function expression can appear anywhere an expression can appear (which is virtually anywhere). A function declaration can only appear at the top level of its enclosing scope, outside of any control-flow statements. So for instance, this is valid:

function bar(x) {
var foo;

if (x) {
foo = function() { // Function expression...
// Do X
};
}
else {
foo = function() { // ...and therefore legal
// Do Y
};
}
foo();
}

...but this is not, and does not do what it looks like it does on most implementations:

function bar(x) {

if (x) {
function foo() { // Function declaration -- INVALID
// Do X
}
}
else {
function foo() { // INVALID
// Do Y
}
}
foo();
}

And it makes perfect sense: Since the foo function declarations are evaluated upon entry into the bar function, before any step-by-step code is executed, the interpreter has no idea which foo to evaluate. This isn't a problem for expressions since they're done during the control-flow.

Since the syntax is invalid, implementations are free to do what they want. I've never met one that did what I would have expected, which is to throw a syntax error and fail. Instead, nearly all of them just ignore the control flow statements and do what they should do if there are two foo function declarations at the top level (which is use the second one; that's in the spec). So only the second foo is used. Firefox's SpiderMonkey is the standout, it seems to (effectively) convert them into expressions, and so which it uses depends on the value of x. Live example.

var functionName = function() {} vs function functionName() {}

The difference is that functionOne is a function expression and so only defined when that line is reached, whereas functionTwo is a function declaration and is defined as soon as its surrounding function or script is executed (due to hoisting).

For example, a function expression:

// TypeError: functionOne is not a functionfunctionOne();
var functionOne = function() { console.log("Hello!");};

What's the difference between a method and a function?

A function is a piece of code that is called by name. It can be passed data to operate on (i.e. the parameters) and can optionally return data (the return value). All data that is passed to a function is explicitly passed.

A method is a piece of code that is called by a name that is associated with an object. In most respects it is identical to a function except for two key differences:

  1. A method is implicitly passed the object on which it was called.
  2. A method is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data).

(this is a simplified explanation, ignoring issues of scope etc.)

What is the (function() { } )() construct in JavaScript?

It’s an Immediately-Invoked Function Expression, or IIFE for short. It executes immediately after it’s created.

It has nothing to do with any event-handler for any events (such as document.onload).

Consider the part within the first pair of parentheses: (function(){})();....it is a regular function expression. Then look at the last pair (function(){})();, this is normally added to an expression to call a function; in this case, our prior expression.

This pattern is often used when trying to avoid polluting the global namespace, because all the variables used inside the IIFE (like in any other normal function) are not visible outside its scope.

This is why, maybe, you confused this construction with an event-handler for window.onload, because it’s often used as this:

(function(){
// all your code here
var foo = function() {};
window.onload = foo;
// ...
})();
// foo is unreachable here (it’s undefined)

Correction suggested by Guffa:

The function is executed right after it's created, not after it is parsed. The entire script block is parsed before any code in it is executed. Also, parsing code doesn't automatically mean that it's executed, if for example the IIFE is inside a function then it won't be executed until the function is called.

Update
Since this is a pretty popular topic, it's worth mentioning that IIFE's can also be written with ES6's arrow function (like Gajus has pointed out in a comment) :

((foo) => {
// do something with foo here foo
})('foo value')

What does (function($) {})(jQuery); mean?

Firstly, a code block that looks like (function(){})() is merely a function that is executed in place. Let's break it down a little.

1. (
2. function(){}
3. )
4. ()

Line 2 is a plain function, wrapped in parenthesis to tell the runtime to return the function to the parent scope, once it's returned the function is executed using line 4, maybe reading through these steps will help

1. function(){ .. }
2. (1)
3. 2()

You can see that 1 is the declaration, 2 is returning the function and 3 is just executing the function.

An example of how it would be used.

(function(doc){

doc.location = '/';

})(document);//This is passed into the function above

As for the other questions about the plugins:

Type 1: This is not a actually a plugin, it's an object passed as a function, as plugins tend to be functions.

Type 2: This is again not a plugin as it does not extend the $.fn object. It's just an extenstion of the jQuery core, although the outcome is the same. This is if you want to add traversing functions such as toArray and so on.

Type 3: This is the best method to add a plugin, the extended prototype of jQuery takes an object holding your plugin name and function and adds it to the plugin library for you.

What does the exclamation mark do before the function?

JavaScript syntax 101: here is a function declaration:

function foo() {}

Note that there’s no semicolon; this is just a function declaration. You would need an invocation, foo(), to actually run the function.

Now, when we add the seemingly innocuous exclamation mark: !function foo() {} it turns it into an expression. It is now a function expression.

The ! alone doesn’t invoke the function, of course, but we can now put () at the end: !function foo() {}(), which has higher precedence than ! and instantly calls the function.

function foo() {}() would be a syntax error because you can’t put arguments (()) right after a function declaration.

So what the author is doing is saving a byte per function expression; a more readable way of writing it would be this:

(function(){})();

Lastly, ! makes the expression return a boolean based on the return value of the function. Usually, an immediately invoked function expression (IIFE) doesn’t explicitly return anything, so its return value will be undefined, which leaves us with !undefined which is true. This boolean isn’t used.

What is the difference between anonymous function and function expression in JavaScript?

I think the better way of understanding is

let sayHi = function someName() {
alert( "Hello" );
}; //This is function expression but with name and function can be called either way like sayHi() or someName().

var anon = function() {
alert('I am anonymous');
}
anon(); //This is also function expression but without name to the function hence it is anonymous function.

An anonymous function is a function without a function name. Only function expressions can be anonymous, function declarations must have a name.

function() {
alert('Hi')
}); // When used as a function expression
(() => {
alert('Hi')
}); // or using the ECMAScript 2015 arrow notation

MDN link to mozzilla developer network for more on functions

Difference between (function(){})(); and function(){}();

Peter Michaux discusses the difference in An Important Pair of Parens.

Basically the parentheses are a convention to denote that an immediately invoked function expression is following, not a plain function. Especially if the function body is lengthy, this reduces surprises,



Related Topics



Leave a reply



Submit