What is the point of using a named function expression? [duplicate] - javascript

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Why use named function expressions?
(5 answers)
Closed 9 years ago.
I'm going through this blog about the difference between function declarations and function expressions.
It gives these two examples. They call the first an "anonymous function expression" and the second a "named function expression."
// anonymous function expression
var a = function(){
return 3;
}
// named function expression
var b = function bar(){
return 3;
}
I tested these two in Chrome's JS console and I see the following:
a()
=> 3
b()
=> 3
bar()
=> bar is not defined
My question is: In the second function expression declaration, what is the point of "bar"? In general, why does one ever use a named function expression?

Some people prefer to do it like this because if errors occur, your functions have names. It's mostly a matter of preference and how often you have trouble with unnamed functions.
You don't normally see it used in a var declaration, but instead when declaring callbacks:
callbackFunction(function success() { ... }, function fail() { ... })
That way you know which argument is which, they're labelled, and if one of them fails you get a precise indication of which one broke.

var b = function bar(){
return 3;
}
bar()
=> bar is not defined
The identifier bar is only available inside of the function. Try
var b = function bar() {
console.log(bar);
}
b();
why does one ever use a named function expression?
To allow referencing a function expression that was not assigned to a reachable or constant variable, e.g. for recursion in an IEFE.
Also, named functions show up different during debugging, e.g. in call stack (trace)s or breakpoint listings. Often you can use a (named) function declaration instead of a function expression, see also http://blog.niftysnippets.org/2010/03/anonymouses-anonymous.html.

Related

What exactly is function expression? [duplicate]

This question already has answers here:
What is the difference between a function expression vs declaration in JavaScript? [duplicate]
(5 answers)
Why JavaScript function declaration (and expression)?
(5 answers)
Why use named function expressions?
(5 answers)
Closed 1 year ago.
I thought before that function expression can be any function that is store in some variable. For example, this is function expression, because function is stored in func variable.
let func = function() {
console.log(5);
};
And here's function expression, because callback function is stored in function's paremeter callback.
function func(callback) {
callback();
};
func(function() {
console.log(5);
});
//That's what I mean:
//let callback = function() {...}
But... recently I've found out that this callback function can also be considered as function expression. Why? This function isn't stored in some variable.
let arr = [18, 50];
let obj = {
name: 'Karina',
};
arr.forEach(function func(value) {
console.log(`${this.name} is ${value} years old`);
}, obj);
So, my question is...What exactly make function function expression?
I thought before that function expression can be any function that is store in some variable.
No. The variable to store to does not matter. The let func = …; is not part of the function expression, the function expression is only the part (expression) that comes in the middle.
let func = function() {
// ^^^^^^^^^^^^
console.log(5);
//^^^^^^^^^^^^^^^^^^
};
//^
This function isn't stored in some variable.
Actually there's no difference between your second and third snippet. You're passing the function constructed from the expression to a function, regardless how that function is declared (with parameters, with rest syntax, without parameters, or as a builtin like forEach).
But yes, you can have function expressions completely without variables, like in
!function() {…}();
// ^^^^^^^^^^^^^^
void function() {…};
// ^^^^^^^^^^^^^^
(function() {…})();
// ^^^^^^^^^^^^^^
Basically, function expressions are just the literal syntax (as in: object literal, string literal) for function objects.
I'm also learning about functional programming and found out that using a function as a value is indeed a function expression, as you said, by assigning an anonymous function to a variable. But I think the main difference relies on the function declaration being hoisted right? So context comes to play and all of that fun stuff :)

javascript named function call throwing error [duplicate]

This question already has answers here:
Why use named function expressions?
(5 answers)
What's the point of naming function expressions if you can't really reference them by the names you give them? [duplicate]
(5 answers)
Closed 5 years ago.
var boo= function foo(){
console.log("I am foo");
}
boo(); // output: I am foo
foo(); // output: Uncaught ReferenceError
I am little confused with javascript named function. Can any one please explain why in above code snippet the foo() function call is throwing the error. Thanks in advance
var boo= function foo(){
There is a clear difference between a function and function expression.
What you have is an expression resolved to a variable. The way you are expecting to work needs to be a function or a variable resolved by a function expression.
From MDN docs
Here is an example of an anonymous function expression (the name is
not used):
var myFunction = function() {
statements
}
It is also possible to provide a name inside the definition in order
to create a named function expression:
var myFunction = function namedFunction(){
statements
}
One of the benefit of creating a named function expression is that in
case we encounted an error, the stack trace will contain the name of
the function, making it easier to find the origin of the error.
As we can see, both example do not start with the function keyword.
Statements involving functions which do not start with function are
function expressions.

Anonymous function expression in Google Chrome [duplicate]

This question already has answers here:
In es2015, `const func = foo => bar` makes `func` a named function, how do you bypass this?
(2 answers)
Closed 6 years ago.
I am using Google Chrome version 52 64-bit.
I found out that if I use anonymous function expression ex.
// Anonymous function expression
var expressionFunc = function(){
return true;
};
The variable expressionFunc will hold the assigned anonymous function,
But it is also adding a name property expressionFunc to this function.
So if I do expressionFunc.name in the console,
It will give me expressionFunc.
From what I know this anonymous function expression should stay anonymous,
And the function referenced by the variable should not contain the variable name in the name property of the function.
Why is chrome assigning name property to an anonymous function?
This page:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Function/name
Says this
Browsers that implement ES6 functions can infer the name of an
anonymous function from its syntactic position. For example:
var f = function() {};
console.log(f.name); // "f"
There's no particular explanation on that page.
This page
http://www.2ality.com/2015/09/function-names-es6.html
Says this
With regard to names, arrow functions are like anonymous function
expressions:
const func = () => {};
console.log(func.name); // func
From now on, whenever you see an anonymous function expression, you
can assume that an arrow function works the same way.
The answer at https://stackoverflow.com/a/37488652/1048572 (referenced by #bergi) is pretty comprehensive, and points to the source in the specification.

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.

Named function expression [duplicate]

This question already has answers here:
Why JavaScript function declaration (and expression)?
(5 answers)
Closed 8 years ago.
I'm assigning a named function expression to a property of an object:
var foo = {};
foo.bar = function bar(){
console.log('bar');
};
foo.bar() => bar
bar() => ReferenceError: bar is not defined
Why can't I call bar() directly, why isn't it defined?
I know that I can simply chain the assignment like var bar = foo.bar = function(){}, so I'm not looking for a work-around or other solution, I'm only interested in why it doesn't work.
I've tested in Chrome console and Node.JS.
Named function expressions are simply not supposed to work that way. The function name is only visible inside the function, not outside.
A function instantiation expression that happens to have a name is not the same thing as a function declaration statement. Those are two distinct syntactic (and semantic) entities in the language.

Categories

Resources