Anonymous vs Named Functions in JavaScript Module Pattern? [duplicate] - javascript

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 6 years ago.
Is there any benefit for the following JavaScript module defenition:
var module = (function(){
var PublicFnc = function(){ // variable declaration
alert('hi');
}
return {
f : PublicFnc
}
})();
module.f();
Over the following:
var module = (function(){
function PublicFnc(){ // function declaration
alert('hi');
}
return {
f : PublicFnc
}
})();
module.f();
Although the second example is more convenient since it is more similar to Java/C# the anonymous methods are used more often and I'm wondering what is the benefit?
#Alexander, thanks for marking the question as duplicate but I tend to leave it open since I'm asking for the benefits within the context of module patterns and not generally

One of the differences between them can be explained using a concept called hoisting
In case:
a(); //you cannot call this function before its definition as here var a is undefined
var a = function(){ //function statement
console.log("Hello World");
}
a(); //this will call the function even before its definition because of hoisting
function a(){ //function definition
console.log("Hello World");
}
Also some the function in the above case is assigned a memory space using that variable.
In hoisting, function definition is hoisted and not the function statement.
Read more about hoisting here http://www.w3schools.com/js/js_hoisting.asp
Also, when to use statement and when to use definition depends on use case and personal preference

Related

Javascript variable declaration, why is this legal? [duplicate]

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 8 years ago.
I just encountered this variable declaration syntax for the first time.
var myVar = (function() {
return 1;
})();
My 2 main questions are..
What is it called, and why is it legal?
Forgive me if this question has been asked before, I tried searching around but I have no idea what this notation is called so I wasn't able to find anything.
Also, I should add, what is the function of the 2 sets of parentheses? The first of which encloses the function, the second of which is empty.
Self executing functions are typically used to encapsulate context and avoid name collusions. Any variable that you define inside the (function(){..})() are not global.
The following code:
var same_name = 1;
var myVar = (function() {
var same_name = 2;
console.log(same_name);
})();
console.log(same_name);
produces this output:
1
2
By using this syntax you avoid colliding with global variables declared elsewhere in you javascript code.
I am not sure what this is called, other than defining an anonymous function and immediately invoking it.
It is perfectly legal, because
Defining an anonymous function is legal.
Invoking it and assigning the return value is also legal.
The end result is that myVar = 1.
This is an anonymous function (also called lambda function) that is being executed immediately with its return value (1) being assigned to a variable (myVar). It's legal because the specification says it is. It is a very common feature in many languages.

When I should use var function and when function [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 9 years ago.
I know what the difference between these two are:
var myFunction = function(a) { ... }
function myFunction2(a) { ... }
I just can't figure out when I should use the first one and when the second one.
I saw this var functionName = function() {} vs function functionName() {} but as I said, I know what the difference between these two are.
well, the two options have pros and cons as told in the duplicate post. If you use:
var functionOne = function () { … }
function functionTwo () { … }
then functionOne won't exist in the block prior to its definition, and is being defined at runtime. Whereas the other option, functionTwo is defined at parse time and can be called anywhere in the program. Another thing that changes is the behavior of this inside the function.
So basically, your question is:
how do I want to scope my function?
if scope does not matter, do I prefer run time or parse time?
To get the full answers to those questions, I really advice you to read and reread the short book from Crockford "Javascript the good parts"‎, and it looks like #wumm's suggested article is pretty relevant as well.

Different ways of naming functions? [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 9 years ago.
In Javascript what is the difference between:
var name = function() { //stuff to do };
{name : function() { //stuff to do } };
function name() { //stuff to do };
As written by Stoyan Stefanov in "JavaScript Patterns":
In function declarations and named function expressions, the name
property is defined. In anonymous function expressions, it depends on
the implementation; it could be undefined (IE) or defined with an
empty string (Firefox, WebKit):
function foo() {} // declaration
var bar = function () {}; // expression
var baz = function baz() {}; // named expression
foo.name; // "foo"
bar.name; // ""
baz.name; // "baz"
The name property is useful when debugging code in Firebug or other
debuggers. When the debugger needs to show you an error in a function,
it can check for the presence of the name property and use it as an
indicator. The name property is also used to call the same function
recursively from within itself. If you were not interested in these
two cases, then an unnamed function expression would be easier and
less verbose.
The case against function declarations and the reason to prefer
function expressions is that the expressions highlight that functions
are objects like all other objects and not some special language
construct.

JavaScript myFunction : function(int x) vs function myFunction(int x)? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the difference between a function expression vs declaration in Javascript?
What is the difference between the two ways to declare a function in JavaScript?
myFunction : function(variable)
{
}
or
function myFunction(variable)
{
}
Your first code snippet is not valid - it only works within an object; example:
var object = {
myFunction: function(variable) { }
};
// object.myFunction();
Basically there are two ways to define a function ins JavaScript:
function myFunction(variable) { }
var myFunction = function(variable) { };
The difference is: The first type of declaration uses the function statement and therefore allows you to use the function before it has been declared. Example:
console.log(myFunction()); // prints test
function myFunction(variable) { return "test"; }
Read more about it here.
This is not possible with the second type of function declaration, which assigns an anonymous function to a variable. The function can't be used before the variable has been declared.
One is a method. The other a function.
Functions are defined
function myfunction() {..}
Methods are defined
myobject.mymethod = function() {...} ;
A method is a property of an object that points to / is a function of that object
Really it depends on how you structure your objects. Functions are usually used in global libraries that are non object specific while methods are tied to objects to execute specific pieces of functionality.

could you explain the function in javascript? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What does this mean? (function (x,y)){…}){a,b); in JavaScript
(function(){
var foo = 'Hello world';
})();
i don't know what's use of it? and what's meaning of it/?
On its own it does nothing except declare a variable that isn't used - it should invoke some other functions to do something useful.
That said, what you have is an immediately invoked function expression, i.e. an anonymous function:
function() { ... }
which is invoked with no parameters:
(f....)();
The rationale is two fold:
it allows the function to be defined and called without giving it a name in the global name space
any variables defined within the function are also held within that scope, and don't pollute the global name space.
It's an anonymous function that executes immediately.
The idea is to create a private scope. Often one would return a closure from the anonymous function that retains access to variables created in that scope.
For example
var greet = (function () {
var foo = 'Hello world';
return function () {
alert(foo);
}
}());
greet();
This calls an anonymous function immediately.
Have a look here: What does this “(function(){});”, a function inside brackets, mean in javascript ?

Categories