Javascript Anonymous Closure - javascript

I have read a lot about closures in Javascript
What are those braces for??
I read on mozilla.org which says closure should be defined as
(function(){...})();
but on http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html, it says the closure function is
(function(){...}());
What's the difference or the latter one is wrong?
what's the purpose of the last ()? Would you put some parameters inside?
I am looking for a good reference.
Edit:
Moreover, there is an example on Mozilla.org
var makeCounter = function() {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
}
};
why the semicolon is needed for this 'function'? If it needs to be invoked immediately after its declaration, a () should be put before the ending semicolon. But there is not.

The syntax
(function(){...})()
is simply an immediately invoked anonymous function. It does not matter how you use your brackets, as the underlying code is a function being declared, and invoked.
Closures are instead used to describe a situation where a function has access to variables declared outside of its scope, accessible via closures
For clarity :
If we have the following function
function hello() {
alert("Hello");
}
We can call the function with the following
hello()
Which invokes the function 'hello'. But if we do not wish to give it a name, but still invoke it, then we can do
(function hello() {
alert("Hello");
})()
Which will do the exact same as the previous example of calling hello
However, in this scenario there is no point in giving the function the name 'hello', so we can simply remove it:
(function() {
alert("Hello");
})()
Which is the notation used in your original question.

Your example shows an Immediately Invoked Function Expression, or IIFE. It says to the interpreter:
here is a function
it has no name
keep it away from the global scope ie 'window'
call it now
Yes, you can put parameters inside the last (). For example:
(
function(username){
alert("Hello " + username);
}
)("John Smith")
Closures are a feature of javascript that allows us to implement data hiding which is roughly equivalent to private variables in languages like C++ or Java.
function getBmiCalculator(height, weight) {
// These are private vars
var height = height;
var weight = weight;
function calculateBmi(){
return weight / (height * height);
}
return calculateBmi;
}
var calc = getBmiCalculator(1.85, 90);
// calc still has access to the scope where height and weight live.
var bmi = calc();
alert(bmi);
In this example, height & weight cannot be garbage-collected until calc is destroyed. The section of memory or "scope" where height & weight exist are "Closed Over"

There is no difference. You can also do so:
true && function(){ /* code */ }();
0,function(){ /* code */ }();
!function(){ /* code */ }(); // Facebook style
~function(){ /* code */ }();
-function(){ /* code */ }();
+function(){ /* code */ }();
// with new
new function(){ /* code */ }
new function(){ /* code */ }() // if you need arguments then use brackets

the grouping operator can surround the function description as without call parentheses, and also including call parentheses. I.e. both expressions below are correct FE:
(function () {})();
(function () {}());
Function Expression

Related

What makes function expressions return a value?

I know that function expressions resolve to a value (not to be confused with what they return [as others cleared up for me in another SO question)—all functions return undefined by default), hence the word "expression," whereas function declarations don't. But I'm not sure what exactly is causing this discrepancy. My initial guess was that it is the variable assignment (given what's to the right of the assignment operator is always an expression [I think]), but function expressions don't require variable assignment. To my knowledge the only other difference (besides resolving to a value) between them and function declarations is that you can omit the function name in a function expression. I'd appreciate any insight.
Refer :https://javascript.info/function-expressions-arrows#function-expression-vs-function-declaration
A Function Expression is created when the execution reaches it and is usable from then on.
Once the execution flow passes to the right side of the assignment let sum = function… – here we go, the function is created and can be used (assigned, called etc) from now on.
Function Declarations are different.
A Function Declaration is usable in the whole script/code block.
In other words, when JavaScript prepares to run the script or a code block, it first looks for Function Declarations in it and creates the functions. We can think of it as an “initialization stage”.
And after all of the Function Declarations are processed, the execution goes on.
As a result, a function declared as a Function Declaration can be called earlier than it is defined.
sayHi("John"); // Hello, John
function sayHi(name) {
alert( `Hello, ${name}` );
}
The Function Declaration sayHi is created when JavaScript is preparing to start the script and is visible everywhere in it.
…If it was a Function Expression, then it wouldn’t work:
sayHi("John"); // error!
let sayHi = function(name) { // (*) no magic any more
alert( `Hello, ${name}` );
};
Function Expressions are created when the execution reaches them. That would happen only in the line (*). Too late.
When a Function Declaration is made within a code block, it is visible everywhere inside that block. But not outside of it.
Sometimes that’s handy to declare a local function only needed in that block alone. But that feature may also cause problems.
For instance, let’s imagine that we need to declare a function welcome() depending on the age variable that we get during runtime. And then we plan to use it some time later.
let age = prompt("What is your age?", 18);
// conditionally declare a function
if (age < 18) {
function welcome() {
alert("Hello!");
}
} else {
function welcome() {
alert("Greetings!");
}
}
// ...use it later
welcome(); // Error: welcome is not defined
That’s because a Function Declaration is only visible inside the code block in which it resides.
Here’s another example:
let age = 16; // take 16 as an example
if (age < 18) {
welcome(); // \ (runs)
// |
function welcome() { // |
alert("Hello!"); // | Function Declaration is available
} // | everywhere in the block where it's declared
// |
welcome(); // / (runs)
} else {
function welcome() { // for age = 16, this "welcome" is never created
alert("Greetings!");
}
}
// Here we're out of curly braces,
// so we can not see Function Declarations made inside of them.
welcome(); // Error: welcome is not defined
What can we do to make welcome visible outside of if?
The correct approach would be to use a Function Expression and assign welcome to the variable that is declared outside of if and has the proper visibility.
Now it works as intended:
let age = prompt("What is your age?", 18);
let welcome;
if (age < 18) {
welcome = function() {
alert("Hello!");
};
} else {
welcome = function() {
alert("Greetings!");
};
}
welcome(); // ok now
Or we could simplify it even further using a question mark operator ?:
let age = prompt("What is your age?", 18);
let welcome = (age < 18) ?
function() { alert("Hello!"); } :
function() { alert("Greetings!"); };
welcome(); // ok now

What are the usage scenarios or advantages of defining functions after the return expression

En example can be found in Twitter'a typeahead.js here:
function () {
// ...
return this.each(initialize);
function initialize() {
// ...
}
}
Questions:
What are the scopes and what function sees what?
What is the reason for using such a construct (usage scenarios and advantages)?
Javascript has function based scope, which means that every thing defined inside a function is available from the first line, since the definition is "hoisted" by the complier.
That goes for both variable and function definitions - variable values however, are not available until after assignment.
You can read all about javascript scoping and hoisting here
This means that the function initialize is available from the first line of the wrapping anonymous function.
There is no real reason, and no advantages, for doing it that way, unless you count the code structure as an advantage.
Personally I don't see any reason to do this. For me even it looks a little bit weird. Martin is right. You should be careful, because the defined variables are not accessible like functions. For example this doesn't work:
var getValue = function(func) {
return func();
}
var f = function() {
return getValue(now);
var now = function() {
return 10;
}
}
alert(f());
However, this works:
var getValue = function(func) {
return func();
}
var f = function() {
return getValue(now);
function now() {
return 10;
}
}
alert(f());

What is the difference between two declarations of module in javascript?

What is the different between two declarations of a module in JavaScript?
One has parentheses around the function and other one doesn't?
One article says that
Notice the () around the anonymous function. This is required by the
language, since statements that begin with the token function are
always considered to be function declarations. Including () creates a
function expression instead.
Both seem to do the same thing when checked.
var person = (function () {
// Private
var name = "Robert";
return {
getName: function() {
return name;
},
setName: function(newName) {
name = newName;
}
};
}());
var person = function () {
// Private
var name = "Robert";
return {
getName: function() {
return name;
},
setName: function(newName) {
name = newName;
}
};
}();
Functions are of two types in JavaScript - declarations and expressions.
This is the difference between the two:
Function declarations are hoisted. This means you can call the function before it appears in the program as declarations in JavaScript are hoisted.
Function expressions can be invoked immediately. A function declaration cannot. This is because expressions express (or return a value). Function expressions express a function.
An example of a function declaration:
foo("bar");
function foo(bar) {
alert("foo" + bar);
}
The above program will work because foo is a function declaration.
foo("bar"); // throws an error, foo is undefined - not a function
var foo = function (bar) {
alert("foo" + bar);
};
The above program will not work as foo is declared as undefined, hoisted and then later assigned the value of a function expression. Hence it's undefined when it's called.
An example of a function expression:
(function (bar) {
alert("foo" + bar);
}("bar"));
The above function will be immediately invoked as it's a function expression.
function (bar) {
alert("foo" + bar);
}("bar"); // throws an error, can't call undefined
The above function will not be immediately invoked as it's a function declaration. Remember, declarations do not express (or return a value). So it's like trying to invoke undefined as a function.
How does a function become an expression?
If a function is used in the context where an expression is expected then it's treated as an expression. Otherwise it's treated as a declaration.
Expressions are expected when:
You're assigning a value to a variable (i.e. identifier = expression).
Inside parentheses (i.e. ( expression )).
As an operand of an operator (i.e. operator expression).
Hence the following are all function expressions:
var foo = function () {};
(function () {});
~function () {};
Everything else is a function declaration. In short if your function is not preceded by anything, it's a declaration.
See this code: https://github.com/aaditmshah/codemirror-repl/blob/master/scripts/index.js#L94
The following function isExpression is used to test whether some arbitrary JavaScript code is an expression or not:
function isExpression(code) {
if (/^\s*function\s/.test(code)) return false;
try {
Function("return " + code);
return true;
} catch (error) {
return false;
}
}
Hope this clears any doubts in your mind.
In short:
A function expression expresses or returns a value (in this case a function). Hence it can be immediately invoked, but it can't be called before it appears in the program.
A function declaration is hoisted. Hence it can be called before it appears in the program. However since it doesn't express any value it can't be immediately invoked.
In the current context there's no difference for the interpreter. Usually preferable way of writing module is by wrapping the function with parentheses:
var person = (function () {
// Private
var name = "Robert";
return {
getName : function () {
return name;
}
};
}());
That's because the syntax is cleaner and it's obviously that you want to invoke the function immediately after it is declared. One more reason is because:
(function () {
//some stuff
}());
will work but
function () {
//some stuff
}();
this wont.
By wrapping the function each time you use common codding style which is usually a good thing :-).
The difference is that when writing:
var foo = (function () {
...
}());
the use of the (superfluous but useful) grouping () is a common coding style to make it clear from very like first line that the right hand side is most likely an immediately invoked function expression (IIFE). However, in the second:
var foo = function () {
...
}();
it doesn't become apparent until you read the last line, which might be quite a few lines down. Until you reach the last line, you probably thought you were reading a plain assignment:
var foo = function () {
...
};
Note that the parenthesis can be used in a plain assignment too:
var foo = (function () {
...
});
but in that case they really are superfluous (and probably misleading due to the convention of using them for IIFEs).
See An Important Pair of Parens.

What does the arguments passed to a javascript closure do?

How do I explain the role of the arguments passed in the beginning vs end of a wrapped Javascript closure as the one shown below?
(function($, window) {
return $(function() {
return alert("js!");
});
})($, window);
The first appearance are function parameters, the second is passing values for those parameters when executing the function.
Keep in mind, the parameters to the function don't need to match the names being passed (this could, in fact, cause confusion later on):
(function(jQuery, w) {
return jQuery(function(){
return alert("js!");
});
})($, window);
Would work the same way.
In that way you are passing arguments that will be safe in the scope from an overwrite in the future. For example:
var a = 1
(function(a){
setTimeout(function(){
console.log('This variable is still safe', a);
},2000)
})(a)
a = 0
console.log('has changed', a)
So in your example you can be sure that $ and window will be that what you are expecting.
It may be easier to explain if you change the argument names and name the function
(function init($, win) {
return $(function() {
return alert("js!");
});
})(jQuery, window);
The init function is being passed the parameters jQuery and window immediately as it's defined, they are available as arguments to the init function as $ and win
If you break it out into the equivalent code, that may also be easier to understand
function init($, win) {
return $(function() {
return alert("js!");
});
}
init(jQuery, window);
The set of parameters on top is where the parameters are recieved, and the set of parameters on the bottom is where they are passed.
They're ensuring that their closed copies of the global variables don't get reassigned outside of the closure. It is a way of protecting your code against other (potentially poorly written) code. Consider this example:
var $ = 'foo';
var blah = (function($) {
return function () {
alert($);
};
})($);
var shizzam = (function() {
return function () {
alert($);
};
})();
// someone evil overwrites my $ var
$ = 'bar';
// blah still works
blah();
// but shizzam is now borked
shizzam();
http://jsfiddle.net/xfTcq/
When a function returns another function it can be enclosed on parentesis to be immediate executed.
The last parenthesis are the passed arguments to it.
You can do some tests do understand:
var a (function(){});
typeof a;
a.toSource()
typeof (function(){});
(function(){}).toSource()

Any way to get the currently executing function object in javascript?

Is there any way to refer to the function object that you're currently executing in? If it's not a method of any object or not called with .call() or .apply(), the this pointer is likely just window, not the function object.
I often use a design pattern like this for global variables that I want scoped to a particular function as this keeps them out of the top level namespace:
function generateRandom() {
if (!generateRandom.prevNums) {
generateRandom.prevNums = {}; // generateRandom.prevNums is a global variable
}
var random;
do {
random = Math.floor((Math.random() * (99999999 - 10000000 + 1)) + 10000000);
} while (generateRandom.prevNums[random])
generateRandom.prevNums[random] = true;
return(random.toString());
}
But, I'd rather not have to spell out the function name every time I want to use a variable scoped to that object. If the name of the function ever changes, there are then a lot of places to change the name.
Is there any way to get the currently executing function object?
Well, you could use arguments.callee()...
https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope/arguments/callee
From MDN:
Description
callee is a property of the arguments object. It can be used to refer
to the currently executing function inside the function body of that
function. This is for example useful when you don't know the name of
this function, which is for example the case with anonymous functions.
Note: You should avoid using arguments.callee() and just give every
function (expression) a name.
BUT...
What you really want are Javascript Prototypes.
function RandomSomethingGenerator()
{
this.prevNums = {};
}
RandomSomethingGenerator.prototype.generate = function() {
var random;
do {
random = Math.floor((Math.random() * (99999999 - 10000000 + 1)) + 10000000);
} while (this.prevNums[random])
this.prevNums[random] = true;
return(random.toString());
};
Why do I say this?
1.) You're dirtying the global space with all those functions.
2.) Even if you like Jani's suggestion, and you want a "static" function like you have now, my suggestion would be the same, but with a twist: Create your global function, and wrap an instance of an object (built from a prototype) inside the closure and make the call to it (so, basically, make yourself a singleton).
As in this (adapted from Jani's answer):
var randomSomething = (function() {
var randomSomethingGenerator = new RandomSomethingGenerator();
return function() {
randomSomethingGenerator.generate();
};
})();
I don't think there's any way to do exactly what you ask, but you could use a closure for your function-local static variables instead.
You can easily achieve this using an IIFE:
var generateRandom = (function() {
//any function's static variables go here
var prevNums = {};
return function() {
//function code goes here
var random;
do {
random = Math....
}
prevNums[random] = true;
return random.toString();
};
})();
You want arguments.callee. From MDN - callee:
callee is a property of the arguments object. It can be used to refer to the currently executing function inside the function body of that function. This is for example useful when you don't know the name of this function, which is for example the case with anonymous functions.
For example:
> foo = function() { console.log(arguments.callee); };
> bar = function() { foo() };
> bar();
function () { console.log(arguments.callee) }
However, I think this is being deprecated. The above link says, "The 5th edition of ECMAScript forbids use of arguments.callee() in strict mode."

Categories