JavaScript function evaluating itself and calling itself at the same time [duplicate] - javascript

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 7 years ago.
I am learning about JavaScript functions on MDN
I came across an example that looks similar to this:
var saySomething = ( function(){console.log("hello")} )();
I have also seen this in the jQuery source.
I have not found any explanation of this style of function calling/definition on the MDN function reference.
I know from running the code that it calls itself immediately upon interpretation by the JavaScript engine.
Is this the Grouping Operator in action? Where it says:
First evaluate the body of this function and return it
Since the parentheses () immediately follow it it gets called ?

Google "Immediately Invoked Function Expression" or "IIFE".
The general syntax looks like this:
(function(){
// do something here
})():
Sometimes you'll see arguments passed in as well. It's basically used to wrap your code so none of your variables leak out into the global namespace.

Related

Self-executing anonymous function conventions [duplicate]

This question already has answers here:
Location of parenthesis for auto-executing anonymous JavaScript functions?
(4 answers)
Closed 8 years ago.
Is there any difference between the following? Do they all work in the same way?
I've seen certain use-cases for .call() but I've never seen an explanation as to why the function call brackets are either inside or after the anonymous function declaration.
(function() {
}());
^^
(function() {
})();
^^
(function() {
}).call();
The first two are the same, and differ by style only*; the last one is different in that it gives you the ability to control what the value of this will be inside the IIFE. For example
(function(){
this.a = 12;
}).call(foo);
will add the property a to the object foo.
*Of course Douglas Crockford has a preference
The location of the () inside or outside the main () doesn't matter in the slightest. (Much) more discussion in this other question, but that question doesn't address the call option you raised.
call requires at least one argument according to the specification, so to be largely the same as your first two options, you'd want:
(function() {
}).call(undefined);
...to be sure some implementation doesn't get uppity with you for not supplying the argument.
I prefer 2nd way. JSLint uses the first way. You should always use .call() with an argument, so the third variant is wrong.
There is no difference between 1 and 2 though.

With jQuery, what is the point of encapsulating a function in round brackets? [duplicate]

This question already has answers here:
What is the purpose of a self executing function in javascript?
(21 answers)
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 8 years ago.
I see this in some HTML files that use jQuery, at the bottom:
(function() {
setTimeout(function(){window.scrollTo(0,0);},0);
})();
What does it mean to put the whole function in round brackets?
The code you gave as example is a self-executing anonymous function.
You can read more about them here.
Relevant text from that article:
What’s useful here is that JavaScript has function level scoping. All variables and functions defined within the anonymous function aren’t available to the code outside of it, effectively using closure to seal itself from the outside world.
(function() {})(); means it is self executing anonymous function. It get called immediately when java script get rendered. More details you can search it.
setTimeout is a function which accepts two parameters:
First parameter: A function
Second parameter: an integer value in milliseconds.
By calling the setTimeout function, the function from first parameter will be called/invoked after the amount of time specified in the second parameter.

javascript module pattern implementations [duplicate]

This question already has answers here:
Location of parenthesis for auto-executing anonymous JavaScript functions?
(4 answers)
Closed 9 years ago.
Is there any differences between javascript modules:
(function(){}())
vs
(function(){})()
First from book "good parts" by Crockford.
Second is code generated with Typescript.
There is no different. Also you can write the third option if your function doesn't return any value
!function(){}()
No, there is no difference between those two functions and how they're called. In both cases, you're creating an anonymous function and executing it immediately.
The only reason the "outer" parens are required is that when the JavaScript parser is expecting to see a statement, if it sees function it assumes what follows will be a function declaration. But we want to give a function expression, so by giving it an initial (, we put it into a state where it's expecting an expression.
But where the () to call the function go (after the } or outside the wrapping parens) doesn't make any difference.
No there is no difference, they both work the same. I tend to use the latter... it just seems to make more sense. (function(){}) defines the function and then you call it with (). In either case though, use a (leading)semicolon before the first (. Reference

Function excuted before creation [duplicate]

This question already has answers here:
Why can I use a function before it's defined in JavaScript?
(7 answers)
Closed 9 years ago.
I am no JavaScript expert, but I found some code like this
a();
function a(){
alert('a');
}
and I was surprised to find it works (I think something like that will not work in Python). I expected that the function a can't be executed before being created. How does interpreter work and why functions can be called before declaration?
This happens because of variable hoisting.
See this answer for more info
JavaScript 'hoisting'
Some docs about this:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting
If you type it like this, it won't work:
a();
a = function(){
alert('a');
}
Code that is within functions and objects will be run whenever that
function or object is called. If it is called from code that is
directly in the head or body of the page then its place in the
execution order is effectively the spot where the function or object
is called from the direct code.
See the reference here.
And in our case the function will give the error as you can see the example here.
It's because function a() is declared via Function Declaration syntax, and Function Declaration are executed right after the script is parsed. With other syntax, Function Expression, like this:
var b = function(){
alert('b');
}
it won't work (see example).
More info: http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/

A simple JavaScript function which is between parenthesis [duplicate]

This question already has answers here:
How does the (function() {})() construct work and why do people use it?
(15 answers)
Closed 9 years ago.
I have downloaded an external JavaScript file and want to create a HTML5 User Interface for it. I don't understand why the JavaScript code (see bellow) initiates his main function like that.
//JavaScript Code
(function(Raphael) {
// some codes here
})(window.Raphael);
Why is that function between parentheses?
What does the "window.Raphael" mean?
This is an example of a self invoking anonymous function.
You are passing in window.Raphael into this function which is essentially "renamed" to Raphael inside the function.
That is an immediately executing function (IIFE). Meaning one thats defined and executed immediately afterwards.
In this case, its also using RaphaelJS which is an SVG library. The IIFE accepts a global variable presumably defined by Raphael that is accessible at window.Raphael

Categories