Javascript Unrecognized Syntax [duplicate] - javascript

This question already has answers here:
What is the purpose of a self executing function in javascript?
(21 answers)
How does this JavaScript/jQuery syntax work: (function( window, undefined ) { })(window)?
(5 answers)
Closed 9 years ago.
I don't understand what the last line of code is doing here. It looks like random parenthesis tagged at the end of the function. I don't understand the syntax.
(function (self, $, undefined) {
self.methodName = function () {
//do stuff
}
})(This.IsTheNameOf.MyJsFile, Jquery);
What I do know: self = namespace organization tool. $ = JQuery. The first thing in the last line of code is the name of the JS file that contains this code. The last line obviously isn't a function call, but it seems to coincide with self and $.
Any knowledge is greatly appreciated!

Leaving out some stuff we have
function (self, $, undefined) {
// ...
}
So, basically, a function (though a name is missing). Now this gets wrapped in
(/* above code here */)(...);
This is a so-called IIFE (Immediately-Invoked Function Expression). In other words: The function is created and immediately invoked. The reason for this is that it creates a scope in which you can have "private" variables. Also, jQuery gets aliased to $ inside that scope for easy reference. Similarly, This.IsTheNameOf.MyJsFile gets aliased to self.
If you look closely, the function expects three arguments, but is only called with two. This forces the last argument to be (the native) undefined, which happens to be the name of that parameter inside the IIFE. This ensures that undefined, inside that scope, has the expected value (older browsers allowed to overwrite it).

Related

Calling an immediately invoked function expression (IIFE) in Javascript [duplicate]

This question already has answers here:
Explain the encapsulated anonymous function syntax
(10 answers)
Location of parenthesis for auto-executing anonymous JavaScript functions?
(4 answers)
strange observation on IIFE in node.js (Windows)
(2 answers)
Closed 15 days ago.
In Javascript, I can define and call an IIFE as such:
(function() {
console.log("foo");
})();
As I understand it, this defines an anonymous function (thus the parentheses surrounding the function definition) and then immediately invokes it (thus the following parentheses, ()).
I noticed that the following also produces the same result:
(function() {
console.log("foo");
}());
Why is that? If I were to skip the parentheses surrounding the entire definition, it would cause an error:
function() {
console.log("foo");
}();
This results in SyntaxError: Function statements require a function name. How does the interpreter understand the second definition and why does it work?

Meaning of !function in Javascript self invoking function [duplicate]

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.

What does function($) mean? [duplicate]

This question already has answers here:
What does function($) mean in javascript?
(3 answers)
Closed 9 years ago.
I just started learning JavaScript. Found a statement function($) { ...} while checking out examples. Can anyone tell me what function($) means?
It means "This defines a function. When it is called: create a local variable called $ and assign the value of the first argument to it."
First off: This creates a function where $ is the first argument passed to it. It could look like this potentially:
function dollar($){
alert($);
}
dollar("hello")
//alerts "hello"
Typically this is used when you want the $ to mean jQuery.
For example:
(function($){
//stuff where $ === jQuery
})(jQuery)
Means that jQuery will be passed into the $ variable for the scope of anything that happens in that function.
This can be useful if you have multiple libraries within the global scope that may use the $ variable, but you have a modular plugin that refers to the necessary library as that and you don't want to rewrite the whole thing.
Note: It does not always mean jQuery but in about 80% of cases it will. Otherwise it is just a convenient way to bind a library to a shorter variable within a certain scope.

What is this syntax? ; (function ($, undefined) [duplicate]

This question already has answers here:
What does (function($) {})(jQuery); mean?
(6 answers)
Closed 9 years ago.
; (function ($, undefined)
{
// all the variables and functions of the js document
})(jQuery);
I've seen this twice now in the jquery/javascript files for a zoom script. I don't understand what this is exactly. I can't seem to google it, I don't remember coming across this on tizag or w3schools while recently learning jquery and js.
There's nothing before or after this code (other than some comments). So I'm utterly lost as to what (function())(jQuery); is or does.
(function ($, undefined)
{
// all the variables and functions of the js document
})(jQuery);
calls a block of code ensuring that inside
$ is usable to refer to jQuery
undefined is undefined (edit: this was useful because undefined could be redefined at that time in the oldest browsers, it's now useless)
and that any minifier can change undefined to a shorter label.
The initial ; ensures you can concatenate this file with another one : without this, you'd have an error executing the concatened file if the one just before was something like
(function (){
})()
This is a way to ensure that $ is indeed the jQuery object and to ensure that any local variables and methods are privately scoped, that is, do not pollute the global namespace.
It is a self-calling anonymous function, with the parameter passed being jQuery, meaning that the $ will be the jQuery object.
Being declared inside a function means that the inner variables and methods will not be visible outside of it.

JavaScript immediate function invocation - why are parenthesis needed around the function? [duplicate]

This question already has answers here:
Explain the encapsulated anonymous function syntax
(10 answers)
Closed 10 years ago.
Why does a function declaration need to be wrapped in parentheses to be immediately invoked? I'm curious as to how the interpreter reads the immediately invoked function when wrapped in parentheses.
I.e.
Why must I do this...
(function() {
// Logic
})();
and not this...
function() {
// Logic
}();
When a function is wrapped in parenthesis it's parsed as an expression - a function expression. Otherwise without them it's parsed as a function declaration. A function declaration requires a name which it sees you have not given it, which in turn causes a syntax error. Moreover, you can't apply () inline to a function declaration in order to call it. The empty parenthesis is a syntax error, but a non-empty parenthesis is an expression which will be evaluated separately from the function.

Categories