This question already has answers here:
What is the difference between a function expression vs declaration in JavaScript? [duplicate]
(5 answers)
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 8 years ago.
What is the difference between
var a = function() {}
and
var a = function b() {}
The latter, b is undefined?
The second one is a named anonymous function - the name will appear in a stacktrace (otherwise in the stacktrace you''ll see just "anonymous function")
The first is an anonymous function expression and the second a named function expression, both valid in Javascript.
For example, it can be used for recursion without arguments.callee (deprecated and not permitted in strict mode), because it refers to itself, no matter where. The scope of the reference is local only to inside the function, that is it isn't accessible globally:
var a = function b(){
return b;
};
function c() {
return c;
}
var d = function e() {
return e();
};
d(); // maximum call stack size exceeded :P
var f = c;
c = null;
f(); // null
a(); // function
b();// undefined not a function
b; // not defined
a()(); // same function again
var a = function() {}
Function name can be omitted. In this case function name is omitted. These functions are called anonymous functions.
Read about javascript scope and anonymous function advantages and disadvantages for details.
Related
This question already has answers here:
What happens when JavaScript variable name and function name is the same?
(6 answers)
Closed 8 months ago.
I want to know the difference between the following two block of codes:
function foo() {
var a = 'private variable';
return function a(){
console.log(a)
}
}
foo()(); // output: function a(){...}
vs
function foo() {
var a = 'private variable';
function a(){};
return () => {console.log(a)}
}
foo()(); // output: private variable
In the first block of code, based on the hoisting, the function a definition should be hoisted, and then var a = 'private variable' rewrite the a, but why the console.log(a) output the function definition?
It's not about hoisting. The first variant does not actually declare a function, it is merely a function expression (i.e., a 'lambda' or a 'closure') which doesn't declare anything within it's own lexical scope. What the 'a' does in that expression is assign the 'name' property of the resulting function object, and make it available to it's body's lexical scope:
e.g. in node:
> const f = function a() {console.log(a);}
undefined
> a
Thrown:
ReferenceError: a is not defined
> f
[Function: a]
> f()
[Function: a]
undefined
See also https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function
I hope below code could help you understand what is happening.
When you use return function a() { ... } it will not considered as function declaration but will be treated as Variable assignment like a = function () { ... }; return a;. And return will execute later a will hold value as function.
As below code you can be sure that assignment want take place until it reaches that line. So when we use foo(1)(); it outputs private variable.
function foo(returnString) {
var a = 'private variable';
if (returnString)
return function() { console.log(a); };
return function a() { console.log(a); };
}
foo()(); // output: function a() { console.log(a); }
foo(1)(); // output: private variable
In your second case it is quite simple. As per Order of precedence
Variable assignment takes precedence over function declaration
Function declarations take precedence over variable declarations
function foo() {
var a = 'private variable';
function a() {};
return () => { console.log(a); }
}
foo()(); // output: private variable
In the first case when you are referencing a in console.log you are actually referencing the function a and it already shadowed over the var = a so you don't have access to it.
On the second option, function a() {} actually moves above the var a = 'private variable' so the code would look like this:
function a() {};
var a;
a = 'private variable';
That is why when you call foo()() your var a = 'private variable'; is shadowing over the function a and you see private variable in terminal.
This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
What is the purpose of a self executing function in javascript?
(21 answers)
What is this JavaScript pattern called and why is it used?
(6 answers)
Closed 3 years ago.
I came across this code, which I don't understand what is going on, and then I removed the IIFE parenthesis and the console.log didn't work anymore, can someone explain what is going on,
It is called the classic module pattern.
Why we want to use it?
var foo = (function(){
var publicAPI = {
bar: function(){
publicAPI.baz()
},
baz: function(){
console.log('baz')
}
}
return publicAPI
})()
foo.baz()
foo.bar()
removing the IIFE parenthesis the console.log doesn't work anymore.
var foo = function(){
var publicAPI = {
bar: function(){
publicAPI.baz()
},
baz: function(){
console.log('baz')
}
}
return publicAPI
})
Thank you a lot in advance.
Given:
foo = function () {}
foo is that function.
Given:
foo = function () {}();
foo is the return value of that function.
If you don't call the function, then foo gets a different value.
In the IIFE you are executing the anonymous function inside the first pair of parenthesis (function(){...})() which returns an object having the bar and baz methods inside it.
so after the execution of the IIFE foo refers the publicAPI object, on which you call the bar and baz methods.
If you remove the parenthesis it just becomes a function statement which does not execute the function or returns the publicAPI object. So foo would refer to the function object and until you execute it foo.bar() or foo.baz() won't be available.
//foo is just referring to the function object if you don't execute it
var foo = function(){
var publicAPI = {
bar: function(){
publicAPI.baz()
},
baz: function(){
console.log('baz')
}
}
return publicAPI
}
//Execute foo to get the returned publicAPI object
foo().bar();
foo().baz();
So surrounding a function definition with a parenthesis converts it to an expression and expressions can be invoked.
(function{...}) --> Expression
You can invoke this expression and assign the returned value to variable (in your case it is foo).
var foo = (function{...})() --> Executed the function expression, foo contains the result of the invokation
This question already has answers here:
Javascript functions like "var foo = function bar() ..."?
(9 answers)
Closed 6 years ago.
Have a function assigned to a variable
var sq = function a(s){return s * s};
Now if i call sq(4) i am getting the result as 16 but if i try to call using the function name a(4) it throws an error "a is not defined"
Can we not call the function by its name once it is assigned to a variable.?
No, because you're using an assignment. You can just do var fn = function () { } or var fn = ()=> { } and get the same thing.
If you created the function and then assigned it to a variable, you could do both.
Basically,
function fn() {...}
var myFunc = fn;
You could then do both:
myFunc();
fn();
This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 7 years ago.
I have been writing functions like
var functionname = function(param)
{
}
rather then
functionname(param)
{
}
does it provide any advantage of the format or any garbage collection happens when i write like the first syntax?
(function() { "use strict"; f(); function f() { console.log(1); }; })();
1
(function() { "use strict"; f(); var f = function() { console.log(1); }; })();
Object expected
Function expressions var name = function() { ... } are not hoisted, while function decarations function name() {...} are.
first of all, u should understand the scope matter for this function.
when u write:
var a = function(){} --> the function is anonymous outside the var a- scope.
it means, that out of this district, the function will not be able to be accessed. another thing is memory usage- here u create a function which takes memory, and a pointer outside the function pointing on it as a soft link.
when u write function a(){} ---> there is a public pointer named a for this function as a hard link.
so, if you want to create a private function- go for it.
i know that it's common to create functions using: function funcName(){);
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What do parentheses surrounding a JavaScript object/function/class declaration mean?
I have found the following code in a website .
var testModule = (function(){
var counter = 0;
return {
incrementCounter: function() {
return counter++;
},
resetCounter: function() {
console.log('counter value prior to reset:' + counter);
counter = 0;
}
};
})();
So it follows the syntax var a = (blah balh..)()
What does it actually mean? What is the meaning of variable declaration like a =()()..
It's defining a single-use function and executing it immediately. The code you provided is named the Module Pattern -- see here for more information about its properties: http://www.yuiblog.com/blog/2007/06/12/module-pattern/
A normal function might be created like this:
var f1 = function() {
console.log('bar');
};
And you could subsequently call it like so:
f1();
But in the example you provided, the function is both defined and executed once, and that function returns an object with two functions: incrementCounter and resetCounter. You can call them like so: testModule.incrementCounter() and testModule.resetCounter()
The Module Pattern is useful when you have a single object and you want to encapsulate some properties which are only available to the functions defined in the closure.
The anonymous function is executed and the return value is assigned to the variable.