Tell us what’s happening:
I converted the original into arrow function but had to make it anon function. How do I name the function using arrow function?
Your code so far
const increment = (number, value = 1) => number + value;
console.log(increment(5, 2)); // returns 7
console.log(increment(5)); // returns NaN
following is the original code
const increment = (function() {
"use strict";
return function increment(number, value) {
return number + value;
};
})();
console.log(increment(5, 2)); // returns 7
console.log(increment(5)); // returns NaN
This is a little misleading. It is true that the following does not work:
myFunc () => // do stuff
However, you can name arrow functions. Take a look at the following snippet:
const myFunc = () => // do stuff
myFunc() // Will call myFunc
For almost all purposes, this works. E.g, if there is an error, the name you gave the function will be in the stack trace found in the console. There is one little shortcoming, illustrated below:
function myFunc() {
// do stuff
}
console.log(myFunc.name) // returns 'myFunc'
const arrowFunc= () => // do stuff
console.log(arrowFunc.name) // returns undefined
However, situations where function.protoype.name is useful are incredibly rare
So, looking at your exmaple, you could write this:
Although, giving a function the same name as its parent function is bad practice, and really, this function doesn’t need to be named at all. So I would much rather write
For the sake of not getting confused with semantics later on.
Binding refers to what context the function’s this runs in. Not the act of assigning it to a variable.
Arrow functions are anonymous function expressions, so therefore can be assigned to a variable.
When we refer to named functions, we mean
// Function declaration - statements don't get assignments
function namedFunc() {}
// Function expression - named (optional)
const namedExpression = function namedExpression() {}