What does this mean in javascript: var obj = (function(){ .... })() [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the purpose of a self executing function in javascript?
Please, can someone explain to me what does that mean in JS:
var obj = (function(){
// code
})()
Thanks

It is an anonymous function that is immediately executed. It's return value is assigned to obj. For example:
var obj = (function () {
return 10;
}()); //Notice that calling parentheses can go inside or outside the others
console.log(obj); //10
They are often used to introduce a new scope so you don't clutter the scope the code is executing in:
var obj = (function () {
var something = 10; //Not available outside this anonymous function
return something;
}());
console.log(obj); //10
Note that since this is a function expression, and not a function declaration, it should have a semi-colon after the closing curly brace.

It's called an immediately instantiated function. It runs the function, and the returned value is assigned to obj. You can create a scope or class with it, in which you can use closures to keep certain variables private within that scope. See John Resigs page on that subject.
So, if the function looks like this:
var obj = (function(n){
return 2+n;
})(3);
The value of obj would be 5.

Related

What is the difference between var foo=function() and function foo() [duplicate]

No matter whether I define the function after the variable
var a = 1;
function a() {};
typeof a // number
Or if I define the function before the variable
function a() {};
var a = 1;
typeof a // number
the final typeof result is always number
I found some explanation about execution context in http://davidshariff.com/blog/what-is-the-execution-context-in-javascript/
Before executing the function code, create the execution context.
......
Scan the context for variable declarations:
If the variable name already exists in the variable object, do nothing and continue scanning.
but this does not seem to work.
So how can I explain it?
It's to do with JavaScript's variable hoisting. Try this instead:
var a = 1;
var a = function() {};
typeof a // function
You're implicitly declaring the variable multiple times by using the function statement 'function a() {};', which as noted by others hoists the variable and behaves unexpectedly due to the order that the browser registers the declarations.
Behind the scenes, this statement instantiates a function object and assigns the result to the variable passed as the function name (reference) but this is done before the explicit var declarations are performed, and so that overrides the implicit declaration. If you just do the following, it will work more intuitively:
var a = 1;
a = function(){};
console.log(typeof a); // function
This is a better option than the multiple var declaration in the other answer from a logical standpoint because (even though you can), it's not a good practice to declare the variable multiple times anyway.
To specifically answer the 'why' for this question: it's so that you can use these kinds of statements to define functions and use them in your explicit declarations, as in
var a = someFunction();
function someFunction(){ return 'someVal'; }
If the function statements weren't parsed and hoisted first, this wouldn't be possible.
As already mentioned, it has to do with the way JavaScript hoisting works. The main issue to notice is that JavaScript will hoist the complete function definition (along with the function body) up to the top, but keeps the variable initialization where it is (only the declaration is hoisted).
So if you write this:
var a = 1;
function a () {
}
it will be translated to:
var a;
function a() {
}
a = 1;
and if you write this:
function a () {
}
var a = 1;
it will be translated to:
function a () {
}
var a;
a = 1;
So no matter what you do, a = 1; will remain at the very bottom.
Please note that the above "translations" should be seen theoretically. JavaScript probably has a way to omit the var a; statement if there is already a function declaration with the same name. And there also might be a defined order (functions get hoisted before variables or the other way around). But all of this doesn't affect the outcome of the variable initialization being the only part that is NOT hoisted at all.

Is a function declaration using function expression and anonymous function? [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 9 years ago.
What is the difference between the following lines of code?
//Function declaration
function foo() { return 5; }
//Anonymous function expression
var foo = function() { return 5; }
//Named function expression
var foo = function foo() { return 5; }
Questions:
What is a named/anonymous function expression?
What is a declared function?
How do browsers deal with these constructs differently?
What do the responses to a similar question (var functionName = function() {} vs function functionName() {}) not get exactly right?
They're actually really similar. How you call them is exactly the same.The difference lies in how the browser loads them into the execution context.
Function declarations load before any code is executed.
Function expressions load only when the interpreter reaches that line of code.
So if you try to call a function expression before it's loaded, you'll get an error! If you call a function declaration instead, it'll always work, because no code can be called until all declarations are loaded.
Example: Function Expression
alert(foo()); // ERROR! foo wasn't loaded yet
var foo = function() { return 5; }
Example: Function Declaration
alert(foo()); // Alerts 5. Declarations are loaded before any code can run.
function foo() { return 5; }
As for the second part of your question:
var foo = function foo() { return 5; } is really the same as the other two. It's just that this line of code used to cause an error in safari, though it no longer does.
Function Declaration
function foo() { ... }
Because of function hoisting, the function declared this way can be called both after and before the definition.
Function Expression
Named Function Expression
var foo = function bar() { ... }
Anonymous Function Expression
var foo = function() { ... }
foo() can be called only after creation.
Immediately-Invoked Function Expression (IIFE)
(function() { ... }());
Conclusion
Douglas Crockford recommends to use function expression in his «JavaScript: The Good Parts» book because it makes it clear that foo is a variable containing a function value.
Well, personally, I prefer to use Declaration unless there is a reason for Expression.
Regarding 3rd definition:
var foo = function foo() { return 5; }
Heres an example which shows how to use possibility of recursive call:
a = function b(i) {
if (i>10) {
return i;
}
else {
return b(++i);
}
}
console.log(a(5)); // outputs 11
console.log(a(10)); // outputs 11
console.log(a(11)); // outputs 11
console.log(a(15)); // outputs 15
Edit:
more interesting example with closures:
a = function(c) {
return function b(i){
if (i>c) {
return i;
}
return b(++i);
}
}
d = a(5);
console.log(d(3)); // outputs 6
console.log(d(8)); // outputs 8
The first statement depends on the context in which it is declared.
If it is declared in the global context it will create an implied global variable called "foo" which will be a variable which points to the function. Thus the function call "foo()" can be made anywhere in your javascript program.
If the function is created in a closure it will create an implied local variable called "foo" which you can then use to invoke the function inside the closure with "foo()"
EDIT:
I should have also said that function statements (The first one) are parsed before function expressions (The other 2). This means that if you declare the function at the bottom of your script you will still be able to use it at the top. Function expressions only get evaluated as they are hit by the executing code.
END EDIT
Statements 2 & 3 are pretty much equivalent to each other. Again if used in the global context they will create global variables and if used within a closure will create local variables. However it is worth noting that statement 3 will ignore the function name, so esentially you could call the function anything. Therefore
var foo = function foo() { return 5; }
Is the same as
var foo = function fooYou() { return 5; }
Though the complete difference is more complicated, the only difference that concerns me is when the machine creates the function object. Which in the case of declarations is before any statement is executed but after a statement body is invoked (be that the global code body or a sub-function's), and in the case of expressions is when the statement it is in gets executed. Other than that for all intents and purposes browsers treat them the same.
To help you understand, take a look at this performance test which busted an assumption I had made of internally declared functions not needing to be re-created by the machine when the outer function is invoked. Kind of a shame too as I liked writing code that way.

difference in defining functions : JavaScript [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 9 years ago.
Do we have any difference between the two mentioned function declaration in JavaScript
//Declaration 1
var foo = function(){
// code goes here
}
and
//Declaration 2
function foo(){
// same code here
}
When i tried to use foo's definition as a class to create other objects
var newObj = new foo();
The Declaration 2 worked but Declaration 1 did not allow me to create and object of this type
this is a function expression:
//Declaration 1
var foo = function(){
// code goes here
}
The func expression in this case is anonymous but assigned to a var foo.
for reference
This is a labeled function :
//Declaration 2
function foo(){
// same code here
}
There's not really any great reason to do expression to var. You
should always try to use labeled statements for constructors,so you
can identify an object's 'type' via its constructor.
people mostly use this where hoisting is needed.Hoisting simply means
calling something before it is defined.
Very very simple example:
foo(); // alerts 'hello'
function foo() {alert('hello');}
V/s
foo(); // throws an error since foo is undefined
var foo = function() {alert('hello');}
First creates a local variable that is assigned a function to. The second declaration creates a function. In first case there is no function to be used for the clients. This is why you can not create objects.
Check this fiddle. It is allowing both declaration:
//Declaration 1
var foo1 = function(){
alert('Declaration 1');
}
//Declaration 2
function foo(){
alert('Declaration 2');
}
var b= new foo1();
var a=new foo();
You can create object of function. here in your case declaration 1 consider foo is a variable so you can not create object of any variable that is why Declaration 2 worked and Declaration 1 did not allow you.
The first one creates an anonymous (nameless) function and assigns it to a variable called foo. The second one declares a function with the name foo. Usually those two forms can be used pretty interchangeable but there are still some differences. The following two are the main differences that come to my mind. The first one might be responsible for what you are experiencing:
Hoisting
In the second example, the complete function definition will be hoisted up to the top of the current scope. So when you write:
var a = new A();
function A() {}
JavaScript will interpret this as:
function A(){}
var a;
a = new A();
...and your code will work fine.
In the first example however, only the variable declaration will be hoisted up. The function body stays where it is. So this:
var a = new A();
var A = function(){};
will be interpreted as this:
var a, A;
a = new A();
A = function(){};
which will lead to an error, since A is still undefined by the time you try to create an instance.
The name property
As I said, the first one creates an anonymous function. That means, if you try to access the name property of that function it will return an empty string:
var A = function(){};
console.log(A.name) //{empty string}
In the second example, your function has the actual name A:
function A(){}
console.log(A.name) //A

Is Function Declaration is only right way to define function inside closure? [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 9 years ago.
What is the difference between the following lines of code?
//Function declaration
function foo() { return 5; }
//Anonymous function expression
var foo = function() { return 5; }
//Named function expression
var foo = function foo() { return 5; }
Questions:
What is a named/anonymous function expression?
What is a declared function?
How do browsers deal with these constructs differently?
What do the responses to a similar question (var functionName = function() {} vs function functionName() {}) not get exactly right?
They're actually really similar. How you call them is exactly the same.The difference lies in how the browser loads them into the execution context.
Function declarations load before any code is executed.
Function expressions load only when the interpreter reaches that line of code.
So if you try to call a function expression before it's loaded, you'll get an error! If you call a function declaration instead, it'll always work, because no code can be called until all declarations are loaded.
Example: Function Expression
alert(foo()); // ERROR! foo wasn't loaded yet
var foo = function() { return 5; }
Example: Function Declaration
alert(foo()); // Alerts 5. Declarations are loaded before any code can run.
function foo() { return 5; }
As for the second part of your question:
var foo = function foo() { return 5; } is really the same as the other two. It's just that this line of code used to cause an error in safari, though it no longer does.
Function Declaration
function foo() { ... }
Because of function hoisting, the function declared this way can be called both after and before the definition.
Function Expression
Named Function Expression
var foo = function bar() { ... }
Anonymous Function Expression
var foo = function() { ... }
foo() can be called only after creation.
Immediately-Invoked Function Expression (IIFE)
(function() { ... }());
Conclusion
Douglas Crockford recommends to use function expression in his «JavaScript: The Good Parts» book because it makes it clear that foo is a variable containing a function value.
Well, personally, I prefer to use Declaration unless there is a reason for Expression.
Regarding 3rd definition:
var foo = function foo() { return 5; }
Heres an example which shows how to use possibility of recursive call:
a = function b(i) {
if (i>10) {
return i;
}
else {
return b(++i);
}
}
console.log(a(5)); // outputs 11
console.log(a(10)); // outputs 11
console.log(a(11)); // outputs 11
console.log(a(15)); // outputs 15
Edit:
more interesting example with closures:
a = function(c) {
return function b(i){
if (i>c) {
return i;
}
return b(++i);
}
}
d = a(5);
console.log(d(3)); // outputs 6
console.log(d(8)); // outputs 8
The first statement depends on the context in which it is declared.
If it is declared in the global context it will create an implied global variable called "foo" which will be a variable which points to the function. Thus the function call "foo()" can be made anywhere in your javascript program.
If the function is created in a closure it will create an implied local variable called "foo" which you can then use to invoke the function inside the closure with "foo()"
EDIT:
I should have also said that function statements (The first one) are parsed before function expressions (The other 2). This means that if you declare the function at the bottom of your script you will still be able to use it at the top. Function expressions only get evaluated as they are hit by the executing code.
END EDIT
Statements 2 & 3 are pretty much equivalent to each other. Again if used in the global context they will create global variables and if used within a closure will create local variables. However it is worth noting that statement 3 will ignore the function name, so esentially you could call the function anything. Therefore
var foo = function foo() { return 5; }
Is the same as
var foo = function fooYou() { return 5; }
Though the complete difference is more complicated, the only difference that concerns me is when the machine creates the function object. Which in the case of declarations is before any statement is executed but after a statement body is invoked (be that the global code body or a sub-function's), and in the case of expressions is when the statement it is in gets executed. Other than that for all intents and purposes browsers treat them the same.
To help you understand, take a look at this performance test which busted an assumption I had made of internally declared functions not needing to be re-created by the machine when the outer function is invoked. Kind of a shame too as I liked writing code that way.

Is function declaration without the "function myFunction() {}" syntax discouraged in javascript? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}
There are two ways to declare a function in Javascript:
Syntax 1:
function myFunction() {
// something awesome
};
Syntax 2:
var myFunction = function() {
// somtehing even more awesomer
};
It seems to me that I come across Syntax 1 a lot more in legacy code than in well written code (but that's purely empiric).
Q: Should prever a syntax over the other, and why ?
The only difference that I can think of is here:
This code does not run: http://jsfiddle.net/JdCRq/
myFunction();
var myFunction = function() {
console.log('test');
};
While this code does: http://jsfiddle.net/JdCRq/1/
myFunction();
function myFunction() {
console.log('test');
}
function blocks, in the context of the second example, seem to be declared (at least by name) before the code is actually run.
The first example is the normal way of declaring a function.
The second example is an anonymous function that is assigned to a variable. This is used when you declare a function as a member of an object, or assign it to the prototype of a class, and is sometimes also used when assigned to a regular variable when the normal way of declaring a function would suffice.
The only practical difference between the examples is that the second way is assigned at runtime. If you redefine a function, that happens when the code is parsed, so only the last one exists:
console.log(f()); // shows 2
function f() { return 1; }
console.log(f()); // shows 2
function f() { return 2; }
console.log(f()); // shows 2
(Although you normally wouldn't redefine a function like that, because it makes the code hard to follow.)
With an anonymous function, it doesn't exist until it is assigned, and if reassigned it changes to the new function:
condole.log(f); // shows undefined
var f = function(){ return 1 };
console.log(f()); // shows 1
f = function(){ return 2 };
console.log(f)); // shows 2
Declaring a function with the function declaration statement (the first way) binds the function name to the function object in such a way as to allow debuggers to show you the name in stack traces. There's really no reason to declare functions with var declarations in simple cases like this. (Sometimes, of course, it's necessary, as when you create functions with other functions.)
Syntactically, it's OK for function instantiation expressions (the second way) to also include a function name that's bound to the function. Unfortunately, some JavaScript runtimes don't handle that case properly and behave somewhat badly, so it's not a good idea.
Using both var and function can have some advantages depending on what you want to achieve, here are some examples;
var f1 = function nonUnique () {return true;},
f2 = function nonUnique () {return false;};
meaning f1.name === f2.name but f1 !== f2
function nonUnique () {return true;};
var f1 = nonUnique;
function nonUnique () {return false;}; // this line changes f1 too
var f2 = nonUnique;
means f1 === f2 and f1 will now return false.
function nonUnique () {return true;};
var f1 = nonUnique,
f2 = f1;
f1 = function nonUnique () {return false;}; // this line changes f1 but not f2
means f1 !== f2; f1 returns false but f2 will return true. nonUnique() will also give true.
This last example is useful of re-using native functions names but keeping them safe.
Also note that variables effectively don't exist before the line with var whereas function syntax will, and see this question, which your question is a duplicate of.

Categories