Difference between closures with parentheses inside vs outside [duplicate] - javascript

This question already has answers here:
Location of parenthesis for auto-executing anonymous JavaScript functions?
(4 answers)
Closed 8 years ago.
Can someone explain what the difference is between these closures? Is there a difference? I haven't previously seen the second example (parentheses inside).
(function(a, b) {
//...
})(x, y);
// Parentheses inside
(function(a, b) {
//...
}(x, y));
And here, is there a difference between these closures? Is there a scenario where there would be a difference?
FOO.Bar = (function() {
//...
})();
FOO.Bar = (function() {
//...
}());

No. In both cases they are exactly the same.
What happens when you wrap your function in parentheses is that is goes from a function declaration to a function expression, which can be invoked immediately.
Whether you invoke it within the parentheses or after does not matter. The "convension" has happened and you can thus invoke it.
And actually you can do this
FOO.Bar = function () {
return 123;
}();
The above is already a function expression since you are assigning an anonymous function to a property Bar on FOO.

Related

Anonymous self-invoking function is automatically passed as an argument to above declared local function. Why? [duplicate]

This question already has answers here:
Semicolon before self-invoking function? [duplicate]
(4 answers)
What are the rules for JavaScript's automatic semicolon insertion (ASI)?
(7 answers)
Uncaught TypeError: (intermediate value)(...) is not a function
(11 answers)
Closed 1 year ago.
I just accidentally discovered this weird thing, and I am wondering if it's a bug, or an expected behavior.
let myfunc = function(a) {
return function localScope(b) {
console.log(a + b + " this")
}
}
(function () {
console.log('test')
})()
The first function returns a function. I never invoke either of them.
Then below, I create a self-invoking function, and what happens is, the self-invoking function is not invoked, instead, it's passed as the a argument to the above myFunc parent function, and then somehow the myFunc is invoked, and for some reason, the returned localScope function is also invoked, and it consoles out the body of the self-invoking function.
However, this does not happen if I declare the self-invoking function differently by enclosing it with brackets, like this:
(function () {
log('test')
}())
Is this like a bug, or is this an expected behavior? Why does declaring the self-invoking function differently makes a difference?
I am guessing this has to do with the scope object, but I have no idea what's happening here. Why is the self-invoking function passed as an argument, and why and how is the local function inside the parent invoked.
Remove some newlines and you can see why:
let myfunc = function(a) {
return function localScope(b) {
console.log(a + b + " this")
}
}(function () {
console.log('test')
})()
And function(){}() is actually valid syntax to call that anonymous function. You can use a defensive semicolon to properly split the statements:
let myfunc = function(a) {
return function localScope(b) {
console.log(a + b + " this")
}
};
(function () {
console.log('test')
})()

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.

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