I'm a javascript newbie trying to wrap my mind around this code.
I got it here http://brackets.clementng.me/post/24150213014/example-of-a-javascript-closure-settimeout-inside
I still have a hard time understanding it. Since it involves some pattern I'm not familiar with.
// output 0-9, seperated by 1 sec delay.
for (var i = 0; i < 10; i++) {
setTimeout(function(x) {
return function() {
console.log(x);
};
}(i), 1000*i);
}
What is the meaning of (i) in this section of code?
function(x) {
return function() {
console.log(x);
};
}(i)
I thought it is an immediately invoked function expression.
But isn't the correct syntax for that is:
(function() {
// some code
})();
That is, indeed, an IIFE. The syntax you quote is an IIFE of 0 arguments; the syntax you asked about is an IIFE of 1 arguments. It will assign i to x in the inner code. Compare:
var print0 = function() {
console.log("Hello!");
};
print0();
is (in isolation) equivalent to
(function() {
console.log("Hello!");
})();
Thus the name: you create a function, then immediately invoke it.
However, if you want an argument, nothing really changes:
var print1 = function(name) {
console.log("Hello, " + name);
};
print1("George");
is (in isolation) equivalent to
(function(name) {
console.log("Hello, " + name);
})("George");
The parentheses here ensure that the function definition will be taken as an expression rather than as a statement. There are other ways to ensure that, a common one being
!function() {
console.log("Hello!");
}();
(But there are reasons to prefer the parentheses.) Since you are using it as an argument to the setTimeout call, it can't possibly be a statement, so these hacks are not necessary. It is still called "immediately invoked function expression", since you are still constructing a function expression and immediately invoking it.
The reason why an IIFE is used here is to "capture" the value of the variable i, rather than the location of x. Without the closure trick, you would get 10 timeouts, all outputting 10 (the value of the location denoted by x when the console.log resolves).
Yes it is, and the (i) is the argument list for the call. Have a look here for a detailed explanation. The grouping parenthesis are unncessary in this case, as it is an argument to the setTimeout function call and therefore an expression anyway.
The term IIFE does not only refer to the statement form of this pattern, where the parenthesis would be necessary.
The parantheses are optional in your example of an immediately invoked function.
(function() {
// some code
})();
Can be re-written as
function() {
// some code
}();
So the i in the example function's call becomes the x in the function definition.
function(x) { // x = 1
return function() {
console.log(x); // x = 1
};
}(1)
I would like to know what this means:
(function () {
})();
Is this basically saying document.onload?
It’s an Immediately-Invoked Function Expression, or IIFE for short. It executes immediately after it’s created.
It has nothing to do with any event-handler for any events (such as document.onload).
Consider the part within the first pair of parentheses: (function(){})();....it is a regular function expression. Then look at the last pair (function(){})();, this is normally added to an expression to call a function; in this case, our prior expression.
This pattern is often used when trying to avoid polluting the global namespace, because all the variables used inside the IIFE (like in any other normal function) are not visible outside its scope.
This is why, maybe, you confused this construction with an event-handler for window.onload, because it’s often used as this:
(function(){
// all your code here
var foo = function() {};
window.onload = foo;
// ...
})();
// foo is unreachable here (it’s undefined)
Correction suggested by Guffa:
The function is executed right after it's created, not after it is parsed. The entire script block is parsed before any code in it is executed. Also, parsing code doesn't automatically mean that it's executed, if for example the IIFE is inside a function then it won't be executed until the function is called.
Update
Since this is a pretty popular topic, it's worth mentioning that IIFE's can also be written with ES6's arrow function (like Gajus has pointed out in a comment) :
((foo) => {
// do something with foo here foo
})('foo value')
It's just an anonymous function that is executed right after it's created.
It's just as if you assigned it to a variable, and used it right after, only without the variable:
var f = function () {
};
f();
In jQuery there is a similar construct that you might be thinking of:
$(function(){
});
That is the short form of binding the ready event:
$(document).ready(function(){
});
But the above two constructs are not IIFEs.
An immediately-invoked function expression (IIFE) immediately calls a function. This simply means that the function is executed immediately after the completion of the definition.
Three more common wordings:
// Crockford's preference - parens on the inside
(function() {
console.log('Welcome to the Internet. Please follow me.');
}());
//The OPs example, parentheses on the outside
(function() {
console.log('Welcome to the Internet. Please follow me.');
})();
//Using the exclamation mark operator
//https://stackoverflow.com/a/5654929/1175496
!function() {
console.log('Welcome to the Internet. Please follow me.');
}();
If there are no special requirements for its return value, then we can write:
!function(){}(); // => true
~function(){}(); // => -1
+function(){}(); // => NaN
-function(){}(); // => NaN
Alternatively, it can be:
~(function(){})();
void function(){}();
true && function(){ /* code */ }();
15.0, function(){ /* code */ }();
You can even write:
new function(){ /* code */ }
31.new function(){ /* code */ }() //If no parameters, the last () is not required
That construct is called an Immediately Invoked Function Expression (IIFE) which means it gets executed immediately. Think of it as a function getting called automatically when the interpreter reaches that function.
Most Common Use-case:
One of its most common use cases is to limit the scope of a variable made via var. Variables created via var have a scope limited to a function so this construct (which is a function wrapper around certain code) will make sure that your variable scope doesn't leak out of that function.
In following example, count will not be available outside the immediately invoked function i.e. the scope of count will not leak out of the function. You should get a ReferenceError, should you try to access it outside of the immediately invoked function anyway.
(function () {
var count = 10;
})();
console.log(count); // Reference Error: count is not defined
ES6 Alternative (Recommended)
In ES6, we now can have variables created via let and const. Both of them are block-scoped (unlike var which is function-scoped).
Therefore, instead of using that complex construct of IIFE for the use case I mentioned above, you can now write much simpler code to make sure that a variable's scope does not leak out of your desired block.
{
let count = 10;
}
console.log(count); // ReferenceError: count is not defined
In this example, we used let to define count variable which makes count limited to the block of code, we created with the curly brackets {...}.
I call it a “Curly Jail”.
It declares an anonymous function, then calls it:
(function (local_arg) {
// anonymous function
console.log(local_arg);
})(arg);
That is saying execute immediately.
so if I do:
var val = (function(){
var a = 0; // in the scope of this function
return function(x){
a += x;
return a;
};
})();
alert(val(10)); //10
alert(val(11)); //21
Fiddle: http://jsfiddle.net/maniator/LqvpQ/
Second Example:
var val = (function(){
return 13 + 5;
})();
alert(val); //18
(function () {
})();
This is called IIFE (Immediately Invoked Function Expression). One of the famous JavaScript design patterns, it is the heart and soul of the modern day Module pattern. As the name suggests it executes immediately after it is created. This pattern creates an isolated or private scope of execution.
JavaScript prior to ECMAScript 6 used lexical scoping, so IIFE was used for simulating block scoping. (With ECMAScript 6 block scoping is possible with the introduction of the let and const keywords.)
Reference for issue with lexical scoping
Simulate block scoping with IIFE
The performance benefit of using IIFE’s is the ability to pass commonly used global objects like window, document, etc. as an argument by reducing the scope lookup. (Remember JavaScript looks for properties in local scope and way up the chain until global scope). So accessing global objects in local scope reduces the lookup time like below.
(function (globalObj) {
//Access the globalObj
})(window);
This is an Immediately Invoked Function Expression in Javascript:
To understand IIFE in JS, lets break it down:
Expression: Something that returns a value
Example: Try out following in chrome console. These are expressions in JS.
a = 10
output = 10
(1+3)
output = 4
Function Expression:
Example:
// Function Expression
var greet = function(name){
return 'Namaste' + ' ' + name;
}
greet('Santosh');
How function expression works:
- When JS engine runs for the first time (Execution Context - Create Phase), this function (on the right side of = above) does not get executed or stored in the memory. Variable 'greet' is assigned 'undefined' value by the JS engine.
- During execution (Execution Context - Execute phase), the funtion object is created on the fly (its not executed yet), gets assigned to 'greet' variable and it can be invoked using 'greet('somename')'.
3. Immediately Invoked Funtion Expression:
Example:
// IIFE
var greeting = function(name) {
return 'Namaste' + ' ' + name;
}('Santosh')
console.log(greeting) // Namaste Santosh.
How IIFE works:
- Notice the '()' immediately after the function declaration. Every funtion object has a 'CODE' property attached to it which is callable. And we can call it (or invoke it) using '()' braces.
- So here, during the execution (Execution Context - Execute Phase), the function object is created and its executed at the same time
- So now, the greeting variable, instead of having the funtion object, has its return value ( a string )
Typical usecase of IIFE in JS:
The following IIFE pattern is quite commonly used.
// IIFE
// Spelling of Function was not correct , result into error
(function (name) {
var greeting = 'Namaste';
console.log(greeting + ' ' + name);
})('Santosh');
we are doing two things over here.
a) Wrapping our function expression inside braces (). This goes to tell the syntax parser the whatever placed inside the () is an expression (function expression in this case) and is a valid code.
b) We are invoking this funtion at the same time using the () at the end of it.
So this function gets created and executed at the same time (IIFE).
Important usecase for IIFE:
IIFE keeps our code safe.
- IIFE, being a function, has its own execution context, meaning all the variables created inside it are local to this function and are not shared with the global execution context.
Suppose I've another JS file (test1.js) used in my applicaiton along with iife.js (see below).
// test1.js
var greeting = 'Hello';
// iife.js
// Spelling of Function was not correct , result into error
(function (name) {
var greeting = 'Namaste';
console.log(greeting + ' ' + name);
})('Santosh');
console.log(greeting) // No collision happens here. It prints 'Hello'.
So IIFE helps us to write safe code where we are not colliding with the global objects unintentionally.
No, this construct just creates a scope for naming. If you break it in parts you can see that you have an external
(...)();
That is a function invocation. Inside the parenthesis you have:
function() {}
That is an anonymous function. Everything that is declared with var inside the construct will be visible only inside the same construct and will not pollute the global namespace.
That is a self-invoking anonymous function.
Check out the W3Schools explanation of a self-invoking function.
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 ().
You cannot self-invoke a function declaration.
This is the self-invoking anonymous function. It is executed while it is defined. Which means this function is defined and invokes itself immediate after the definition.
And the explanation of the syntax is: The function within the first () parenthesis is the function which has no name and by the next (); parenthesis you can understand that it is called at the time it is defined. And you can pass any argument in this second () parenthesis which will be grabbed in the function which is in the first parenthesis. See this example:
(function(obj){
// Do something with this obj
})(object);
Here the 'object' you are passing will be accessible within the function by 'obj', as you are grabbing it in the function signature.
Start here:
var b = 'bee';
console.log(b); // global
Put it in a function and it is no longer global -- your primary goal.
function a() {
var b = 'bee';
console.log(b);
}
a();
console.log(b); // ReferenceError: b is not defined -- *as desired*
Call the function immediately -- oops:
function a() {
var b = 'bee';
console.log(b);
}(); // SyntaxError: Expected () to start arrow function, but got ';' instead of '=>'
Use the parentheses to avoid a syntax error:
(function a() {
var b = 'bee';
console.log(b);
})(); // OK now
You can leave off the function name:
(function () { // no name required
var b = 'bee';
console.log(b);
})();
It doesn't need to be any more complicated than that.
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 code
var same_name = 1;
var myVar = (function() {
var same_name = 2;
console.log(same_name);
})();
console.log(same_name);
produces this output:
2
1
By using this syntax you avoid colliding with global variables declared elsewhere in your JavaScript code.
It is a function expression, it stands for Immediately Invoked Function Expression (IIFE). IIFE is simply a function that is executed right after it is created. So insted of the function having to wait until it is called to be executed, IIFE is executed immediately. Let's construct the IIFE by example. Suppose we have an add function which takes two integers as args and returns the sum
lets make the add function into an IIFE,
Step 1: Define the function
function add (a, b){
return a+b;
}
add(5,5);
Step2: Call the function by wrap the entire functtion declaration into parentheses
(function add (a, b){
return a+b;
})
//add(5,5);
Step 3: To invock the function immediatly just remove the 'add' text from the call.
(function add (a, b){
return a+b;
})(5,5);
The main reason to use an IFFE is to preserve a private scope within your function. Inside your javascript code you want to make sure that, you are not overriding any global variable. Sometimes you may accidentaly define a variable that overrides a global variable. Let's try by example. suppose we have an html file called iffe.html and codes inside body tag are-
<body>
<div id = 'demo'></div>
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
</body>
Well, above code will execute with out any question, now assume you decleard a variable named document accidentaly or intentional.
<body>
<div id = 'demo'></div>
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
const document = "hi there";
console.log(document);
</script>
</body>
you will endup in a SyntaxError: redeclaration of non-configurable global property document.
But if your desire is to declear a variable name documet you can do it by using IFFE.
<body>
<div id = 'demo'></div>
<script>
(function(){
const document = "hi there";
this.document.getElementById("demo").innerHTML = "Hello JavaScript!";
console.log(document);
})();
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
</body>
Output:
Let's try by an another example, suppose we have an calculator object like bellow-
<body>
<script>
var calculator = {
add:function(a,b){
return a+b;
},
mul:function(a,b){
return a*b;
}
}
console.log(calculator.add(5,10));
</script>
</body>
Well it's working like a charm, what if we accidently re-assigne the value of calculator object.
<body>
<script>
var calculator = {
add:function(a,b){
return a+b;
},
mul:function(a,b){
return a*b;
}
}
console.log(calculator.add(5,10));
calculator = "scientific calculator";
console.log(calculator.mul(5,5));
</script>
</body>
yes you will endup with a TypeError: calculator.mul is not a function iffe.html
But with the help of IFFE we can create a private scope where we can create another variable name calculator and use it;
<body>
<script>
var calculator = {
add:function(a,b){
return a+b;
},
mul:function(a,b){
return a*b;
}
}
var cal = (function(){
var calculator = {
sub:function(a,b){
return a-b;
},
div:function(a,b){
return a/b;
}
}
console.log(this.calculator.mul(5,10));
console.log(calculator.sub(10,5));
return calculator;
})();
console.log(calculator.add(5,10));
console.log(cal.div(10,5));
</script>
</body>
Output:
TL;DR: Expressions can be enclosed in parenthesis, which would conflict with function calling if the expression and block forms of function were combined.
I like counter-examples because they paint a great picture of the logic, and noone else listed any. You might ask, "Why can't the browser see function(){}() and just assume its an expression?" Let's juxtapose the issue with three examples.
var x;
// Here, fibonacci is a block function
function fibonacci(x) {
var value = x < 2 ? x : fibonacci(x-1) + fibonacci(x-2);
if (x === 9) console.log("The " + x + "th fibonacci is: " + value);
return value;
}
(x = 9);
console.log("Value of x: " + x);
console.log("fibonacci is a(n) " + typeof fibonacci);
Observe how things change when we turn the function into an expression.
var x;
// Here, fibonacci is a function expression
(function fibonacci(x) {
var value = x < 2 ? x : fibonacci(x-1) + fibonacci(x-2);
if (x === 9) console.log("The " + x + "th fibonacci is: " + value);
return value;
})
(x = 9);
console.log("Value of x: " + x);
console.log("fibonacci is a(n) " + typeof fibonacci);
The same thing happens when you use the not-operator instead of parenthesis because both operators turn the statement into an expression:
var x;
// Here, fibonacci is a function expression
! function fibonacci(x) {
var value = x < 2 ? x : fibonacci(x-1) + fibonacci(x-2);
if (x === 9) console.log("The " + x + "th fibonacci is: " + value);
return value;
}
(x = 9);
console.log("Value of x: " + x);
console.log("fibonacci is a(n) " + typeof fibonacci);
By turning the function into an expression, it gets executed by the (x = 9) two lines down from it. Thanks to separate behaviors for expression functions and block functions, both examples run fine without ambiguity (specs-wise).
Name Scoping
Another important observation is that named block functions are visible to the entire scope, whereas function expressions are only visible to themselves. In other words, fibonacci is only visible to the last console.log when it is a block in the first example. In all three examples, fibonacci is visible to itself, allowing fibonacci to call itself, which is recursion.
Arrow Functions
Another aspect to the logic is arrow functions. The specs would have had to include arbitrary rules and exceptions for arrow functions if the definitions of block and expression functions were merged together:
function hello() {console.log("Hello World")}
(x) => console.log("hello " + x)
console.log("If you are reading this, no errors occurred");
Although function blocks work fine, function expressions followed by an arrow function produce a syntax error:
! function hello() {console.log("Hello World")}
(x) => console.log("hello " + x)
console.log("If you are reading this, no errors occurred");
Here, it is ambiguous whether the (x) on line two is calling the function on the preceding line or whether it is the function arguments for an arrow function.
Note that arrow functions have been indeed to the ECMAScript standard over the years and were not a factor in the initial design of the language; my point is that a differentiation between expression and block functions helps JavaScript syntax to be a little more logical and coherent.
Self-executing anonymous function. It's executed as soon as it is created.
One short and dummy example where this is useful is:
function prepareList(el){
var list = (function(){
var l = [];
for(var i = 0; i < 9; i++){
l.push(i);
}
return l;
})();
return function (el){
for(var i = 0, l = list.length; i < l; i++){
if(list[i] == el) return list[i];
}
return null;
};
}
var search = prepareList();
search(2);
search(3);
So instead of creating a list each time, you create it only once (less overhead).
It is called IIFE - Immediately Invoked Function Expression. Here is an example to show it's syntax and usage. It is used to scope the use of variables only till the function and not beyond.
(function () {
function Question(q,a,c) {
this.q = q;
this.a = a;
this.c = c;
}
Question.prototype.displayQuestion = function() {
console.log(this.q);
for (var i = 0; i < this.a.length; i++) {
console.log(i+": "+this.a[i]);
}
}
Question.prototype.checkAnswer = function(ans) {
if (ans===this.c) {
console.log("correct");
} else {
console.log("incorrect");
}
}
var q1 = new Question('Is Javascript the coolest?', ['yes', 'no'], 0);
var q2 = new Question('Is python better than Javascript?', ['yes', 'no', 'both are same'], 2);
var q3 = new Question('Is Javascript the worst?', ['yes', 'no'], 1);
var questions = [q1, q2, q3];
var n = Math.floor(Math.random() * questions.length)
var answer = parseInt(prompt(questions[n].displayQuestion()));
questions[n].checkAnswer(answer);
})();
Already many good answers here but here are my 2 cents :p
You can use IIFE (Immediately Invoked Function Expression) for:
Avoiding pollution in the global namespace.
Variables defined in IIFE (or even any normal function) don't overwrite definitions in global scope.
Protecting code from being accessed by outer code.
Everything that you define within the IIFE can be only be accessed within the IIFE. It protects code from being modified by outer code. Only what you explicitly return as the result of function or set as value to outer variables is accessible by outer code.
Avoid naming functions that you don't need to use repeatedly.
Though it's possible to use a named function in IIFE pattern you don't do it as there is no need to call it repeatedly, generally.
For Universal Module Definitions which is used in many JS libraries. Check this question for details.
IIFE is generally used in following fashion :
(function(param){
//code here
})(args);
You can omit the parentheses () around anonymous function and use void operator before anonymous function.
void function(param){
//code here
}(args);
IIFE (Immediately invoked function expression) is a function which executes as soon as the script loads and goes away.
Consider the function below written in a file named iife.js
(function(){
console.log("Hello Stackoverflow!");
})();
This code above will execute as soon as you load iife.js and will print 'Hello Stackoverflow!' on the developer tools' console.
For a Detailed explanation see Immediately-Invoked Function Expression (IIFE)
One more use case is memoization where a cache object is not global:
var calculate = (function() {
var cache = {};
return function(a) {
if (cache[a]) {
return cache[a];
} else {
// Calculate heavy operation
cache[a] = heavyOperation(a);
return cache[a];
}
}
})();
The following code:
(function () {
})();
is called an immediately invoked function expression (IIFE).
It is called a function expression because the ( yourcode ) operator in Javascript force it into an expression. The difference between a function expression and a function declaration is the following:
// declaration:
function declaredFunction () {}
// expressions:
// storing function into variable
const expressedFunction = function () {}
// Using () operator, which transforms the function into an expression
(function () {})
An expression is simply a bunch of code which can be evaluated to a single value. In case of the expressions in the above example this value was a single function object.
After we have an expression which evaluates to a function object we then can immediately invoke the function object with the () operator. For example:
(function() {
const foo = 10; // all variables inside here are scoped to the function block
console.log(foo);
})();
console.log(foo); // referenceError foo is scoped to the IIFE
Why is this useful?
When we are dealing with a large code base and/or when we are importing various libraries the chance of naming conflicts increases. When we are writing certain parts of our code which is related (and thus is using the same variables) inside an IIFE all of the variables and function names are scoped to the function brackets of the IIFE. This reduces chances of naming conflicts and lets you name them more careless (e.g. you don't have to prefix them).
The reason self-evoking anonymous functions are used is they should never be called by other code since they "set up" the code which IS meant to be called (along with giving scope to functions and variables).
In other words, they are like programs that "make classes', at the beginning of program. After they are instantiated (automatically), the only functions that are available are the ones returned in by the anonymous function. However, all the other 'hidden' functions are still there, along with any state (variables set during scope creation).
Very cool.
In ES6 syntax (posting for myself, as I keep landing on this page looking for a quick example):
// simple
const simpleNumber = (() => {
return true ? 1 : 2
})()
// with param
const isPositiveNumber = ((number) => {
return number > 0 ? true : false
})(4)
This function is called self-invoking function. A self-invoking (also called self-executing) function is a nameless (anonymous) function that is invoked(Called) immediately after its definition. Read more here
What these functions do is that when the function is defined, The function is immediately called, which saves time and extra lines of code(as compared to calling it on a seperate line).
Here is an example:
(function() {
var x = 5 + 4;
console.log(x);
})();
An immediately invoked function expression (IIFE) is a function that's executed as soon as it's created. It has no connection with any events or asynchronous execution. You can define an IIFE as shown below:
(function() {
// all your code here
// ...
})();
The first pair of parentheses function(){...} converts the code inside the parentheses into an expression.The second pair of parentheses calls the function resulting from the expression.
An IIFE can also be described as a self-invoking anonymous function. Its most common usage is to limit the scope of a variable made via var or to encapsulate context to avoid name collisions.
This is a more in depth explanation of why you would use this:
"The primary reason to use an IIFE is to obtain data privacy. Because JavaScript's var scopes variables to their containing function, any variables declared within the IIFE cannot be accessed by the outside world."
http://adripofjavascript.com/blog/drips/an-introduction-to-iffes-immediately-invoked-function-expressions.html
Normally, JavaScript code has global scope in the application. When we declare global variable in it, there is a chance for using the same duplicate variable in some other area of the development for some other purpose. Because of this duplication there may happen some error. So we can avoid this global variables by using immediately invoking function expression , this expression is self-executing expression.When we make our code inside this IIFE expression global variable will be like local scope and local variable.
Two ways we can create IIFE
(function () {
"use strict";
var app = angular.module("myModule", []);
}());
OR
(function () {
"use strict";
var app = angular.module("myModule", []);
})();
In the code snippet above, “var app” is a local variable now.
Usually, we don't invoke a function immediately after we write it in the program.
In extremely simple terms, when you call a function right after its creation, it is called IIFE - a fancy name.
Today I came a cross the self executing functions, than somehow I ended up knowing about
Self-Executing Anonymous Functions, then I've read this article: http://briancrescimanno.com/how-self-executing-anonymous-functions-work/
The thing is that I don't know WHY to use Self-Executing Anonymous Functions because if I need to do something like:
var test = "a";
(function(foo) {
alert(foo);
})(test);
I could just make something like:
var test = "a";
alert(foo);
Or did I miss anything?
also this can be done to any code inside the function, but I used alert() to make simple
Update:
Even thought I've already accepted and answer I would like to share something I've found, if anyone came across this question later :)
Using this notation we can also make an endless loop like following:
(function loop(){
// do something here
loop();
)();
There are a couple of reasons why one would use an IIFE:
1) No littering
var a = 'foo';
alert(a);
vs
(function() {
var a = 'foo';
alert(a);
}())
Both examples do the same thing, but in the second example there is no a variable inside the outer scope.
2) State capturing
var a = 'foo';
window.setTimeout(function() { alert(a); }, 1);
a = 'bar';
vs
var a = 'foo';
window.setTimeout( (function(a_copy) {
return function() { alert(a_copy); }
}(a)), 1);
a = 'bar';
The first example alerts bar, while the second alerts foo. You will find this technique used especially with loops.
Your initial example isn't worth to be executed in an anonymous function, so its a bad example to understand WHY to use this technique. Here is a good example to explore state capturing:
var list = [{id: 1, data: null}, ...];
for (var i = 0; i < list.length; i++) {
(function(item) {
// start async request, for each item in the list, in the order of the list
asyncAjax("get-data-from-somewhere.json?what=" + list[i].id, function (response) {
// thats the on success callback, which gets executed when the server responded
// each item will have different response times, therefore the order of response is various
// if we would use simply list[i].data, it wouldn't work correctly, because "i" would has the value of list.length, because the iteration has been finished yet.
item.data = response;
});
})(list[i]); // the function will preserve the reference to the list item inside, until the function has been fully executed
}
When writing sync. code, you can always fallback to classic object oriented style of structering your code. So you can avoid closures / instant-anonymous function calls. But as soon as you use async. mechanics, closures get very handy and make your code looking more clean, off course only if you can read and understand closures :)
By the way, you could also simply write:
function(private) {}(outer)
is the same as
(function(private) {})(outer)
but the second is better, because its simply more obvious for the reader.
The syntax you describe is commonly referred to as an "immediately invoked function expression", or IIFE.
One of the common use cases is to emulate private variables:
var ns = (function () {
var x = 1; // "private"
return {
getX: function () {
return x;
}
}
}());
ns.getX(); // 1
ns.x; // undefined because x is "private"
In that example the x variable is local to the IIFE. It's not directly accessible outside of it. However, since it is referred to by the getX method, which is accessible outside of the IIFE (because it's part of the returned object) a reference to x is kept alive. This is what is usually meant by the term "closure".
Self executing functions are not really useful if you just do an alert inside.
Consider something like this:
(function(foo) {
var a = ..
// do something with a and foo
})(test);
The advantage here is that a is "private" inside the method and cannot be used outside the method. So a doesn't end up as a global variable and can't be overwritten by some other piece of javascript which uses a variable of the same name.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What do empty parentheses () after a function declaration do in javascript?
I am looking at some Javascript code and trying to figure out what }(); right after return num+10 means. Does that mean the function will get executed immediately? Where can I get more information about this.
function addToTen(num) {
return function() {
return num+10;
}();
}
addToTen(5); // 15
Thanks,
Venn.
Yes, but only if it's a function expression, which is different from a function declaration. A function declaration is how your first function is defined:
function foo(){
}
If you add () after this, you get a Syntax Error. If the function is defined as a function expression, adding a set of parenthesis immediately executes it. Functions are expressions whenever they are not defined as above, e.g.:
(function(){}());
var x = function(){}();
return function(){}();
Your actual example is just... odd, and pointless. It's almost a classic closure example, something like:
function addTo(x){
return function(y){
return x + y;
}
}
var addToTen = addTo(10);
addToTen(5); // 15;
but your actual example is equivalent to just:
function addToTen(num){
return num + 10;
}
and all the extra stuff is completely unnecessary.
Yes, it means the function object is evaluated.
Just like with any other function, you have two ways of looking at it:
var myFunction = function(val) {
return val + 1;
}
To return the function object, or send it somewhere else, I just say myFunction
If I wish to execute it, I say myFunction()
In this closure or decorator, whatever, that you've described above, rather than return the function object itself, you're returning the value of executing that function immediately, hence the () afterwards.
Yes, it's executed immediately, but the usage doesn't make any sense in this example.
Often used for anonymous functions creating a closure.
see Why do you need to invoke an anonymous function on the same line?
One place where I use it a lot:
(function($) {
// secure way to ensure no conflict between $ (jQuery)
// and another js-framework can happen
$...
})(jQuery);
I've written (in JavaScript) an interactive read-eval-print-loop that is encapsulated
within an object. However, I recently noticed that toplevel function definitions specified to the interpreter do not appear to be 'remembered' by the interpreter. After some diagnostic work, I've reduced the core problem to this:
var evaler = {
eval: function (str)
{
return eval(str);
},
};
eval("function t1() { return 1; }"); // GOOD
evaler.eval("function t2() { return 2; }"); // FAIL
At this point, I am hoping that the following two statements wil work as expected:
print(t1()); // => Results in 1 (This works)
print(t2()); // => Results in 2 (this fails with an error that t2 is undefined.)
What I get instead is the expected value for the t1 line, and the t2 line fails with an error that t2 is unbound.
IOW: After running this script, I have a definition for t1, and no defintion for t2. The act of calling eval from within evaler is sufficiently different from the toplevel call that the global definition does not get recorded. What does happen is that the call to
evaler.eval returns a function object, so I'm presuming that t2 is being defined and stored in some other set of bindings that I don't have access to. (It's not defined as a member in evaler.)
Is there any easy fix for this? I've tried all sorts of fixes, and haven't stumbled upon one that works. (Most of what I've done has centered around putting the call to eval in an anonymous function, and altering the way that's called, chainging __parent__, etc.)
Any thoughts on how to fix this?
Here's the result of a bit more investigation:
tl;dr: Rhino adds an intermediate scope to the scope chain when calling a method on an instance. t2 is being defined in this intermediate scope, which is immediately discarded. #Matt: Your 'hacky' approach might well be the best way to solve this.
I'm still doing some work on the root cause, but thanks to some quality time with jdb, I now have more understanding of what's happening. As has been discussed, a function statement like function t1() { return 42; } does two things.
It creates an anonymous instance of a function object, like you'd get with the expression function() { return 42; }
It binds that anonymous function to the current top scope with the name t1.
My initial question is about why I'm not seeing the second of these things happen when I call eval from within a method of an object.
The code that actually performs the binding in Rhino appears to be in the function org.mozilla.javascript.ScriptRuntime.initFunction.
if (type == FunctionNode.FUNCTION_STATEMENT) {
....
scope.put(name, scope, function);
For the t1 case above, scope is what I've set to be my top-level scope. This is where I want my toplevel functions defined, so this is an expected result:
main[1] print function.getFunctionName()
function.getFunctionName() = "t1"
main[1] print scope
scope = "com.me.testprogram.Main#24148662"
However, in the t2 case, scope is something else entirely:
main[1] print function.getFunctionName()
function.getFunctionName() = "t2"
main[1] print scope
scope = "org.mozilla.javascript.NativeCall#23abcc03"
And it's the parent scope of this NativeCall that is my expected toplevel scope:
main[1] print scope.getParentScope()
scope.getParentScope() = "com.me.testprogram.Main#24148662"
This is more or less what I was afraid of when I wrote this above: " In the direct eval case, t2 is being bound in the global environment. In the evaler case, it's being bound 'elsewhere'" In this case, 'elsewhere' turns out to be the instance of NativeCall... the t2 function gets created, bound to a t2 variable in the NativeCall, and the NativeCall goes away when the call to evaler.eval returns.
And this is where things get a bit fuzzy... I haven't done as much analysis as I'd like, but my current working theory is that the NativeCall scope is needed to ensure that this points to evaler when execution in the call to evaler.eval. (Backing up the stack frame a bit, the NativeCall gets added to the scope chain by Interpreter.initFrame when the function 'needs activation' and has a non-zero function type. I'm assuming that these things are true for simple function invocations only, but haven't traced upstream enough to know for sure. Maybe tomorrow.)
Your code actually is not failing at all. The eval is returning a function which you never invoke.
print(evaler.eval("function t2() { return 2; }")()); // prints 2
To spell it out a bit more:
x = evaler.eval("function t2() { return 2; }"); // this returns a function
y = x(); // this invokes it, and saves the return value
print(y); // this prints the result
EDIT
In response to:
Is there another way to create an interactive read-eval-print-loop than to use eval?
Since you're using Rhino.. I guess you could call Rhino with a java Process object to read a file with js?
Let's say I have this file:
test.js
function tf2() {
return 2;
}
print(tf2());
Then I could run this code, which calls Rhino to evaluate that file:
process = java.lang.Runtime.getRuntime().exec('java -jar js.jar test.js');
result = java.io.BufferedReader(java.io.InputStreamReader(process.getInputStream()));
print(result.readLine()); // prints 2, believe it or not
So you could take this a step further by WRITING some code to eval to a file, THEN calling the above code ...
Yes, it's ridiculous.
The problem you are running into is that JavaScript uses function level scoping.
When you call eval() from within the eval function you have defined, it is probably creating the function t2() in the scope of that eval: function(str) {} function.
You could use evaler.eval('global.t2 = function() { return 2; }'); t2();
You could also do something like this though:
t2 = evaler.eval("function t2() { return 2; }");
t2();
Or....
var someFunc = evaler.eval("function t2() { return 2; }");
// if we got a "named" function, lets drop it into our namespace:
if (someFunc.name) this[someFunc.name] = someFunc;
// now lets try calling it?
t2();
// returns 2
Even one step further:
var evaler = (function(global){
return {
eval: function (str)
{
var ret = eval(str);
if (ret.name) global[ret.name] = ret;
return ret;
}
};
})(this);
evaler.eval('function t2() { return 2; }');
t2(); // returns 2
With the DOM you could get around this function-level scoping issue by injecting "root level" script code instead of using eval(). You would create a <script> tag, set its text to the code you want to evaluate, and append it to the DOM somewhere.
Is it possible that your function name "eval" is colliding with the eval function itself? Try this:
var evaler = {
evalit: function (str)
{
return window.eval(str);
},
};
eval("function t1() { return 1; }");
evaler.evalit("function t2() { return 2; }");
Edit
I modified to use #Matt's suggestion and tested. This works as intended.
Is it good? I frown on eval, personally. But it works.
I think this statement:
evaler.eval("function t2() { return 2; }");
does not declare function t2, it just returns Function object (it's not function declaration, it's function operator), as it's used inside an expression.
As evaluation happens inside function, scope of newly created function is limited to evaler.eval scope (i.e. you can use t2 function only from evaler.eval function):
js> function foo () {
eval ("function baz() { return 'baz'; }");
print (baz);
}
js> foo ();
function baz() {
return "baz";
}
js> print(baz);
typein:36: ReferenceError: baz is not defined
https://dev.mozilla.jp/localmdc/developer.mozilla.org/en/core_javascript_1.5_reference/operators/special_operators/function_operator.html
https://dev.mozilla.jp/localmdc/developer.mozilla.org/en/core_javascript_1.5_reference/statements/function.html
I got this answer from the Rhino mailing list, and it appears to work.
var window = this;
var evaler = {
eval : function (str) {
eval.call(window, str);
}
};
The key is that call explicitly sets this, and this gets t2 defined in the proper spot.