What is this format of function called? [duplicate] - javascript

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
What is the purpose of a self executing function in javascript?
(21 answers)
Closed 7 years ago.
function animator(shapes, $timeout) {
(function tick() {
var i;
var now = new Date().getTime();
var maxX = 600;
var maxY = 600;
var now = new Date().getTime();
$timeout(tick, 30);
})(); // What is this for?
}
Here I don't understand the functionality. I am new to this kind of script. Inside of the main function is like ()(). What is this for?

This is an IIFE, Immediately-invoked function expression.
Why use an IIFE?
Why?: An IIFE removes variables from the global scope. This helps
prevent variables and function declarations from living longer than
expected in the global scope, which also helps avoid variable
collisions.
Why?: When your code is minified and bundled into a single file for
deployment to a production server, you could have collisions of
variables and many global variables. An IIFE protects you against both
of these by providing variable scope for each file.

I don't know if it has a separate name, it's just immediately executed.
Instead of function a(){..}; a() you can do (function(){..})()
Useful for scoping the vars inside, while placing/executing it right where you want it, also you don't have to invent a name for it.

(function(){console.log('test')})() will call function immediately. So if you will write this statement then it will be called immediately and prints test on console.

This is a self-invoking function as #lix pointed out.
Function expressions can be made "self-invoking".
A self-invoking expression is invoked (started) automatically, without being called.
Function expressions will execute automatically if the expression is followed by ().

Related

Difference between function declerations [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 2 years ago.
What is the difference between this (a 'standalone' function):
function standaloneFunction () {
console.log('standaloneFunction runs, success')
}
standaloneFunction()
...and this (a function inside a variable):
let variableFunction = function variableFunction () {
console.log('function inside let has same name as the variable, runs? - yep, does.')
}
variableFunction()
Is it a problem that the variable and the function share the same name?
it doesnt seem so - i speculate this is because it has something to do how variables
and functions are saved in memory? Functions in their entirety, and variables only their declaration?
When i do console.log(this), i can't find the 'variableFunction' in the execution
context of 'this' - however, 'standaloneFunction' does appear.
Have you, as a beginner, also asked yourself such questions? Am i being too picky about such details?
Should i already use es6 syntax?
Please also don't hold back with any advice regarding articulating my question.
Thanks to everyone who has taken their time to read this.
The first is a function declaration, which will be hoisted. The second is a named function expression, but I think an anonymous function expression would be better in this case since there’s no need to name the function, e.g. let variableFunction = function() {…}.
Please see What is the difference between a function expression vs declaration in JavaScript?

Why javascript function parentheses can not access the outside? [duplicate]

This question already has answers here:
Why a Name Function Expression not available outside function body [duplicate]
(3 answers)
How do JavaScript closures work?
(86 answers)
Closed 7 years ago.
I'm curious, why not just javascript function scope it? Why just add a parenthesis can not access it? My guess is that the parentheses and javascript related operations, but do not know exactly why this child principle and design?
(function test(){
console.log( test );
})();
test();//Uncaught ReferenceError: test is not defined IE8- is ok
or
(function test(){
console.log( test );
});
test();//Uncaught ReferenceError: test is not defined IE8- is ok
When you wrap a function in parentheses like you did, it does put it in a new scope.
It also acts like a return value, which is why it can be called as an IIFE, or Immediately Invoking Function Expression.
Another way to re-write it, which will make more sense is like so:
var myFunc = (function test(){
alert('Hello!');
});
myFunc(); // Works!
test(); // Doesn't work!
To learn more about this, you should read about IIFE - Immediately-invoked function expression.
The short version - the function runs in its own scope, unless you pass parameters to it, like so:
(function test(x) {
alert(x); //alerts "yey!";
})("yey!");

Javascript variable declaration, why is this legal? [duplicate]

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 8 years ago.
I just encountered this variable declaration syntax for the first time.
var myVar = (function() {
return 1;
})();
My 2 main questions are..
What is it called, and why is it legal?
Forgive me if this question has been asked before, I tried searching around but I have no idea what this notation is called so I wasn't able to find anything.
Also, I should add, what is the function of the 2 sets of parentheses? The first of which encloses the function, the second of which is empty.
Self executing functions are typically used to encapsulate context and avoid name collusions. Any variable that you define inside the (function(){..})() are not global.
The following code:
var same_name = 1;
var myVar = (function() {
var same_name = 2;
console.log(same_name);
})();
console.log(same_name);
produces this output:
1
2
By using this syntax you avoid colliding with global variables declared elsewhere in you javascript code.
I am not sure what this is called, other than defining an anonymous function and immediately invoking it.
It is perfectly legal, because
Defining an anonymous function is legal.
Invoking it and assigning the return value is also legal.
The end result is that myVar = 1.
This is an anonymous function (also called lambda function) that is being executed immediately with its return value (1) being assigned to a variable (myVar). It's legal because the specification says it is. It is a very common feature in many languages.

difference between javascript function declaration [duplicate]

This question already has an answer here:
Anonymous function vs normal function
(1 answer)
Closed 9 years ago.
I know this type of question gets asked a lot, but I haven't seen any question with this type of declaration
(function(){
myFuncName=function(myVar){
// some logic
};
}());
how does that differ from
function myFuncName(myVar){
// some logic
}
The first one is an anonymous function and there is no way you can reference to and call it later on, so you just executes instantly ( ) once it had been created!
(function(){
alert(1)
}())
The second one is a reference function that you can call it anytime later. It wont gets executed unless you call it explicitly
What your doing is creating an anonymous function that also has a closure in it. Read more about closures here.
Basically a closure means that you have declared a function inside of another function. Which will let you access local variables after the first function exits.
Normally you would not be able to do this since they would be out of scope.
As for the other part. You can find a very useful guide to what's happening here Why do you need to invoke an anonymous function on the same line?.
To sum it up though, you have created an anonymous self-invoking function expression.
The self-invoking comes from the fact that () immediately follows the function expression.
Here's a link which explains the the function declarations in javascript.

could you explain the function in javascript? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What does this mean? (function (x,y)){…}){a,b); in JavaScript
(function(){
var foo = 'Hello world';
})();
i don't know what's use of it? and what's meaning of it/?
On its own it does nothing except declare a variable that isn't used - it should invoke some other functions to do something useful.
That said, what you have is an immediately invoked function expression, i.e. an anonymous function:
function() { ... }
which is invoked with no parameters:
(f....)();
The rationale is two fold:
it allows the function to be defined and called without giving it a name in the global name space
any variables defined within the function are also held within that scope, and don't pollute the global name space.
It's an anonymous function that executes immediately.
The idea is to create a private scope. Often one would return a closure from the anonymous function that retains access to variables created in that scope.
For example
var greet = (function () {
var foo = 'Hello world';
return function () {
alert(foo);
}
}());
greet();
This calls an anonymous function immediately.
Have a look here: What does this “(function(){});”, a function inside brackets, mean in javascript ?

Categories