Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does !function in Javascript mean? [duplicate]

Tags:

Sorry for posting this but !function is not google-able and I did not find it in my JavaScript code.

Here is how Twitter uses it:

<a href="https://twitter.com/share" class="twitter-share-button" data-url="http://google.com" data-text="Google says">Tweet</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script> 

from https://twitter.com/about/resources/buttons#

like image 682
Barka Avatar asked Feb 13 '12 20:02

Barka


People also ask

What does function () mean in JavaScript?

The function statement declares a function. A declared function is "saved for later use", and will be executed later, when it is invoked (called). In JavaScript, functions are objects, and they have both properties and methods. A function can also be defined using an expression (See Function Definitions).

How do you duplicate a function in JavaScript?

clone = function() { var newfun = new Function('return ' + this. toString())(); for (var key in this) newfun[key] = this[key]; return newfun; };

What does () => mean in JavaScript?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.

Can you define a function twice in JavaScript?

functions are data in memory stack, so when you define another function with the same name, it overrides the previous one. Show activity on this post. Well obviously you're not meant to define the same function twice. However, when you do, the latter definition is the only 1 that applies.


1 Answers

It is short-hand or alternative of self-invoking anonymous function:

(function(){   // code })(); 

Can be written:

!function(){   // code }(); 

You can also use + instead of !.

If you simply did:

function(){   // code }(); 

That will create problems, that's why you need to add ! before it which turns the function declaration into function expression.

Quoting docs, section 12.4:

An ExpressionStatement cannot start with the function keyword because that might make it ambiguous with a FunctionDeclaration.

To better understand the concept, you should check out:

  • Function Declarations vs. Function Expressions
like image 128
Sarfraz Avatar answered Oct 23 '22 07:10

Sarfraz