Tell us what’s happening:
Hi! I’m having trouble wrapping my head around this part. I’m not sure what it means by not naming the function because to me, it seems like the name has just been shifted over to the const. Could someone explain to me in what cases this is better than naming the function? I did some research and found that if the function is only used in one place, it shouldn’t have a name, but doesn’t myFunc technically have a name anyway in the form of a const? Thanks!
You have a point. The function can be accessed by calling myFunc (serves as a reference to the function in memory) even if the function expression has a name (name only useful within its body) and it’s also been stored in a variable or constant. For example,
const myFunc = function aFunc() {...}
The above can only be accessed by myFunc, but within the functions body u can call aFunc.
They’re effectively identical in most modern JS runtimes, for practical purposes. If you assign a function expressions to a variable, as you’re doing there, they implicitly do have a name, which is, as you say, the name of the variable. This is very easy to demonstrate:
There are differences, but they’re very slight: you can freely use functions as values in Javascript, normally passing them to other functions, for example:
[1,2,3].forEach((v) => console.log("Value: ", v))
That’s using an anonymous function (without any name there). But equally, could do
function logValue (v) {
console.log("Value: ", v);
}
[1,2,3].forEach(logValue);
Using a function declaration. And it does exactly the same thing.
Few things that are different:
anonymous functions can be used to create immediately invoked function expressions, ie a function that is immediately executed, which is useful in a number of contexts.
function declarations are hoisted to the top of the scope (this means you can call them [in the code] before they are defined [later on in the code]). Function expressions are not, they go in order, and you’ll get a syntax error if you try to access them before they’re defined (they’re attached to a variable, so it’s exactly the same rules as variables).
arrow functions don’t have arguments or the [non-standard] caller or callee properties, you’ll get a syntax error if you try to access them.