Named function expressions in JavaScript
Suppose we have such a functional expression:
let test = function() {
console.log('!');
};
test(); // shows '!'
Let's name our function func
:
let test = function func() {
console.log('!');
};
test();
As you already know, this name does not refer to the function:
let test = function func() {
console.log('!');
};
test(); // shows '!'
func(); // throws an error
Why we give a name to function if it won't be available? The thing is that this name will not be available outside the function, but it will be available inside this function.
Let's check:
let test = function func() {
console.log(func); // the function will output its own source code
};
test(); // call the function
Let's call our function within itself:
let test = function func() {
console.log('!'); // shows '!'
func(); // calls iself
};
test();
If you run this code, then an infinite number of alerts will be displayed in the console.
In fact, our function can be called
internally not only as func
,
but also as test
:
let test = function func() {
console.log('!');
test(); // calls iself
};
test();
What is the difference? The difference
is that the name test
is just a
variable. While the script is running,
our function may be written to another
variable or passed as a parameter - in
this case, the connection between the
variable test
and the function
may be lost.
The name func
is hardcoded to
the function specifically so that we
can refer to our function within itself.
Such Function Expressions with a function name are called named function expressions.