Javascript: Benefit of naming functions when assigning variables in an object? [duplicate] - javascript

This question already has answers here:
Why use named function expressions?
(5 answers)
Closed 8 years ago.
I noticed people in my company like to name functions when assigning it to variables. What are the benefits when it works exactly the same without naming them?
function TargetingForm() {
'use strict';
this.setPristine = function setPristine() {
...
}
//vs
this.setPristine = function() {
...
}
}

In order to ensure the name of the function appears in stack traces when debugging (as opposed to showing up as "anonymous function").
However, many modern javascript engines can derive a useful name for stack traces even when the function is declared anonymously in an assignment expression such as in your second example.

One thing that I can think of (if I am right!) is that you might need to call the function from itself (recursion).
For example you can do this:
function TargetingForm() {
'use strict';
this.setPristine = function setPristine() {
// You can do this
if (someConditionIsTrue) {
setPristine();
}
}
//vs
this.setPristine = function() {
// You can't do the same here!
}
}

Related

Why would I give a function a name, when using the module pattern [duplicate]

This question already has answers here:
Why use named function expressions?
(5 answers)
Closed 8 years ago.
I looked at the jsf.js file of Mojarra 2.2.8 and saw them using the module pattern. Something like this:
name.space = function() {
var utilFunction = function utilFunction() {
// some implementation
};
return {
exposedFunction: function exposedFunction() {
// using utilFunction
}
};
}();
Is there any benefit of giving the functions a name? As opposed to use anonymous functions. They are bound to either a variable or a property of the same name anyway.
Is this some kind of best practice? Does it maybe improve debugging?
I'm just asking, because I usually see the module pattern used with anonymous functions, and was now wondering.
I think it is justified only when using anonymous functions for obvious reading, for example:
async.waterfall[
function makeOne () {},
function makeTwo () {},
];

javascript function declarations and differences in scope [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
What is the difference between a function expression vs declaration in JavaScript? [duplicate]
(5 answers)
Closed 8 years ago.
I couldnT find an answer easily, so even if this question is a dupe, the answers donT come up using these keywords.
I want to know the difference between the different way of declaring functions in a sample app.js
var foo = function()
{
//..
}
function bar()
{
//..
}
var baz= function()
{
//..
}
function qux()
{
//..
}
// other??
I m also not clear about the scope where I can use each function. Thanks!
There are four ways to create a function in JavaScript.
Function declaration
This will create a variable foo in the current scope and assign a named function to it.
function foo () {
}
Function declarations are hoisted so it doesn't matter where, in the applicable scope, you put them. It is considered good coding practise to define them before you use them though.
Anonymous function expression
This will create a function without a name and use it in an expression. In this example it is assigned to the variable something.
something = function () {
};
Named function expression
This is the same as an anonymous function expression except that it has a name, creates a variable of that name in the scope of itself and is horribly broken in older versions of Internet Explorer.
something = function foo () {
};
Function constructor
Do not use function constructors. They are eval by another name. You can read about them on MDN if you're interested.

Why is the function with in parenthesis? [duplicate]

This question already has answers here:
Why is this function wrapped in parentheses, followed by parentheses? [duplicate]
(6 answers)
Closed 8 years ago.
Question:
Why is the function wrapped in a parenthesis? I have taken this code out of parenthesis and it works with no trouble.
What is the benefit of having the code in a (function() { ...Code Here...})(); like it is in the following example?
Code:
(function() {
"use strict";
// Doesn't work because strict mode
// enforces the fact that the second example shouldn't work
if (true) {
function fn1() {
// This won't run
console.log("doesn't work -- have a great Die Hard Day XIII");
};
fn1();
}
})();
Code Here: What would sending the JQuery word as a parameter do for this namespace. I know that the reason that the function is enclosed in (...) is to create a namespace. I guess a better question would be as to why one would pass in a variable, but I would imagine that would be in case another namespace needed the variable.
( function( $ ) {
// Init Skrollr
var s = skrollr.init({
render: function(data) {
//Debugging - Log the current scroll position.
//console.log(data.curTop);
}
});
} )( jQuery );
I have taken this code out of parenthesis and it works with no trouble.
That’s not correct; it can’t run (or even be parsed) by itself. JavaScript sees function in a place where a function declaration can be and assumes it’s a function declaration. Parentheses are used to force the context to be an expression. The practice is redundant if it’s unambiguously a function literal – say, in a variable declaration – but many find it more readable. There’s a jsHint option to enforce it, for example.
Because then they are calling it:
(function() { ... })();
^^

Awkward way of executing JavaScript code [duplicate]

This question already has answers here:
How do JavaScript closures work?
(86 answers)
Why is this function wrapped in parentheses, followed by parentheses? [duplicate]
(6 answers)
Closed 9 years ago.
In the Google tutorial for implementing Google+ sign-in in Flask application, I discovered that the developer often uses an awkward way of executing JavaScript code:
Instead of doing
var a = foo(bar);
I see this:
var a = (function() {
return foo(bar);
})();
What is the reason to do it the weird way?
This is a poor example. Consider the following:
var a = (function() {
var ret = {};
ret.test = "123";
function imPrivate() { /* ... */ }
ret.public = function() {
imPrivate();
}
return ret;
})();
console.log(a)
a will contain the varible test and the function public, however you can not access imPrivate. This is the common way to handle public vs private variables;
See Why is this function wrapped in parentheses, followed by parentheses? for more info.
var a = (function() {
return foo(bar);
})();
In this case this is really unnecessary, but this is not wrong and it will not throw an error.
But IIF some times uses like module pattern:
var a = (function() {
/* some other code in own scope */
return foo(bar);
})();
In this case IIF is just a module which exports something outside.
The closure function is used to encapsulate some of the attributes / methods in the function. Much like the private / public principle from other languages.
You can find more on this topic here under Module Pattern

What is the difference between these two? [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Are named functions preferred over anonymous functions in JavaScript? [duplicate]
(4 answers)
Closed 9 years ago.
I saw the following JavaScript functions works exactly same, Then what is the difference between them other than syntax.
The function are:
var functionName=function(){
//some code here
};
function functionName(){
//some code here
}
I call them in the same way as:
functionName();
Please dont' tell me there syntax is different, Other than that is there any difference like
1)speed of execution
2)Memory utilization etc.
Thanks in advance!
This has been answered many times in StackOverflow. It is just the way of naming. So taking up some points from the answers, I would say:
Function declarations and variable declarations are always moved ("hoisted") invisibly to the top of their containing scope by the JavaScript interpreter. Function parameters and language-defined names are, obviously, already there.
Advantages & Disadvantages:
There are few advantages to naming functions:
names for meta analysis. functionInstance.name will show you the name.
Far more importantly, the name will be printed in stack traces.
names also help write self documenting or literate code.
There is a single disadvantage to named functions expressions
IE has memory leaks for NFE
Another main difference
The difference is that functionTwo is defined at parse-time for a script block, whereas functionOne is defined at run-time. For example:
<script>
// Error
functionOne();
var functionOne = function() {
}
</script>
<script>
// No error
functionTwo();
function functionTwo() {
}
</script>
References
var functionName = function() {} vs function functionName() {}
Are named functions or anonymous functions preferred in JavaScript?
Named function expressions demystified
Function Declarations vs. Function Expressions.
var functionName = function() {} vs function functionName() {}
1st one is Named Function Expressions, which should return some value to the caller.
2nd one is just a function, it's upto you whether you return value or not

Categories

Resources