what does !function in Javascript mean? [duplicate] - javascript

This question already has answers here:
What does the exclamation mark do before the function?
(8 answers)
Closed 5 years ago.
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:
Tweet
<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#

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

they're negating the result, not the function itself:
!function( x ){ return x }( true );
!true
false
In reality, it's a slightly compressed form of:
(function(){}())
since it requires 1 less character. The reason it's needed is that you can't call a function declaration directly, e.g. this is invalid:
function(){}()
but adding the ! at the beginning turns it into a function expression and makes it work.

It's usually used to work around a quirk in the JavaScript syntax. This gives a syntax error:
function() {
}();
It's read as a function declaration (like function foo () {}), rather than a function expression. So adding the ! before it, or wrapping it in parentheses, forces the parser to understand that it's an expression.

Related

why use a logical operator in javascript function declaration [duplicate]

This question already has answers here:
What does the exclamation mark do before the function?
(8 answers)
Closed 6 years ago.
I'm looking at some JavaScript code and I can't figure out why a logical operator (!) is being used in function declaration. This is a tiny extract:
! function (a) {
! function (a)
{
"use strict";
a.Shorthand = {
UI: {},
helpers: {},
Data: {}
}
}(window), ...
}(!1);
I'm pretty sure its an IIFE (when complete) and it's main purpose is minification but that's as far as I go. I've not come across any explanation.
When the rest of the code is there it all works.
thanks
It's about function expression needed instead of function declaration for IIFE. If function is used as expression it can be invoked imidiatelly. If it's not a part of an expression it can't so this code won't work:
function(){}()
while this will work:
!function(){}()
(function(){}())
(function(){})()
var a = function(){}()

Is the underscore.js IIFE syntax valid? [duplicate]

This question already has answers here:
Reason behind this self invoking anonymous function variant
(5 answers)
Closed 8 years ago.
I just took a look at the underscore.js source code and when i strip the source code down to its bare containing IIFE it looks like this:
(function() {
}.call(this));
I always used the syntax with outer parantheses (function() {}).call(this); and wondered if this syntax is also valid and common?
If you're asking about the location of the outer ) specifically, then whether it's located immediately after the closing brace or after the entire expression doesn't matter for the most part. Either way doesn't make a difference to how the IIFE is executed.
The only difference here is the .call(this), which is invoked as a member of the function expression — a typical IIFE has just the inner parentheses immediately following the closing brace. The reason .call(this) is used is detailed in a number of other answers including this one.

Why is the function with in parenthesis? [duplicate]

This question already has answers here:
Why is this function wrapped in parentheses, followed by parentheses? [duplicate]
(6 answers)
Closed 8 years ago.
Question:
Why is the function wrapped in a parenthesis? I have taken this code out of parenthesis and it works with no trouble.
What is the benefit of having the code in a (function() { ...Code Here...})(); like it is in the following example?
Code:
(function() {
"use strict";
// Doesn't work because strict mode
// enforces the fact that the second example shouldn't work
if (true) {
function fn1() {
// This won't run
console.log("doesn't work -- have a great Die Hard Day XIII");
};
fn1();
}
})();
Code Here: What would sending the JQuery word as a parameter do for this namespace. I know that the reason that the function is enclosed in (...) is to create a namespace. I guess a better question would be as to why one would pass in a variable, but I would imagine that would be in case another namespace needed the variable.
( function( $ ) {
// Init Skrollr
var s = skrollr.init({
render: function(data) {
//Debugging - Log the current scroll position.
//console.log(data.curTop);
}
});
} )( jQuery );
I have taken this code out of parenthesis and it works with no trouble.
That’s not correct; it can’t run (or even be parsed) by itself. JavaScript sees function in a place where a function declaration can be and assumes it’s a function declaration. Parentheses are used to force the context to be an expression. The practice is redundant if it’s unambiguously a function literal – say, in a variable declaration – but many find it more readable. There’s a jsHint option to enforce it, for example.
Because then they are calling it:
(function() { ... })();
^^

how does jquery make the $ do what it does? [duplicate]

This question already has answers here:
Immediate function invocation syntax
(3 answers)
Closed 9 years ago.
In order to use the $ symbol in jquery and not have to use jQuery.functionname, we use this
(function($) {
})(jQuery);
(In drupal, you actually have to specify this implicitly).
I don't understand this javascript syntax, why is there an initial parentheses? How is the (jQuery) at the end used?
It's just an anonymous function with an argument that's automatically invoked.
For example, if we were to expand it out a bit you'd end up with something like this:
var anon = function($) {
...
};
anon(jQuery);
The $ is a valid identifer in JavaScript and we pass in the existing jQuery object into the function for use through $, as it could be replaced later.
All that's doing is declaring an anonymous function and executing it immediately, passing in one argument (jQuery) into the function. That argument is given the name $ which can be used throughout the scope of the function.
The brackets around the function aren't strictly necessary in all contexts; see the comment under this answer for details. The gist is that they're needed here to make the function behave like an expression instead of a statement (function declaration).

Is this jQuery related, and what does this mean? [duplicate]

This question already has answers here:
What does the exclamation mark do before the function?
(8 answers)
Closed 9 years ago.
I have been searching, but no clues... or I haven't search the proper way (so please excuse me if duplicate)
Does the following code, mean: If there is no jQuery defined, or no document ready?
!function ($) {
///
!function ($) {
$(function(){ // I know this is an alias to $(document).ready()
.....
}(window.jQuery) // Ending of !function
I'm asking, because I saw it here: http://twitter.github.io/bootstrap/assets/js/application.js and have no I really don't know what it means.
In this case, ! is being used because it's an operator, so the rest of the line will be treated as an expression rather than a statement. This is a way of writing an immediately invoked function expression. The more common idioms can be found here:
Javascript immediately invoked function patterns
! on a function(){}() simply flips (or negates) the value that's returned after immediately calling the function that's defined. Notice that immediately after the function definition, at the very last line, it says (window.jQuery) — that's passing jQuery as the argument to the function and calling it immediately.
But in this case it doesn't appear to do anything important since the return value won't be used anyway. The function will still be executed though.
Also, it says this at the top of the file:
// NOTICE!! DO NOT USE ANY OF THIS JAVASCRIPT
// IT'S ALL JUST JUNK FOR OUR DOCS!
// ++++++++++++++++++++++++++++++++++++++++++
So that's evidence further that it's not meant to serve any real purpose.

Categories

Resources