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 :)
Related
This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 8 months ago.
const func = () => {
someFunction() // error here
return function someFunction() {
console.log('hello')
}
}
func()
I've created closure and wanted to check hoisting inside of func function. Each time when you create function declaration it hoists your variable up to the top. Why is someFunction not hoisted?
When you put a function after return statement, it no longer is a function declaration, but rather a function expression. Unlike declarations, function expressions are not hoisted.
Function expressions in JavaScript are not hoisted, unlike function
declarations.
- MDN
You have a (named) function expression in your return statement. This function is not a function statement and because of this, it is not hoisted.
Another reason is, a function expression has no name. That means, you can not access it by the a name outside of the function. The name of a function expression is only available inside of the function with it name (for example for recursions).
This question already has answers here:
What does the exclamation mark do before the function?
(8 answers)
Closed 4 years ago.
Importance of using ! in this code
var testValue;
!function test() { testValue = 3; }();
console.log(testValue);
The ! indicates to the interpreter to parse what follows as an expression rather than as what would otherwise be a function declaration. Function declarations can't be invoked on the same line, so without the !, a SyntaxError would be thrown:
var testValue;
function test() { testValue = 3; }();
console.log(testValue);
Only function expressions can be immediately invoked. Though, to indicate a function expression, it would probably be clearer to use parentheses around the function rather than !, and there isn't all that much point to naming the function test if the function name isn't used anywhere, eg:
var testValue;
(() => {
testValue = 3;
})();
console.log(testValue);
Functions are not automatically objects. You should define it inside brackets or assign it to a variable. If you use ! for function definition. It means
!(function(){console.log("hi");})
Now you can insert () to run that function.
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.
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.
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.