Functions can either be named or unnamed (anonymous functions):
var namedSum = function sum (a, b) { // named
return a + b;
}
var anonSum = function (a, b) { // anonymous
return a + b;
}
namedSum(1, 3);
anonSum(1, 3);
4 4
But their names are private to their own scope:
var sumTwoNumbers = function sum (a, b) {
return a + b;
}
sum(1, 3);
Uncaught ReferenceError: sum is not defined
Named functions differ from the anonymous functions in multiple scenarios:
name
property differentlyWhen using an anonymous function, the function can only be called after the line of declaration, whereas a named function can be called before declaration. Consider
foo();
var foo = function () { // using an anonymous function
console.log('bar');
}
Uncaught TypeError: foo is not a function
foo();
function foo () { // using a named function
console.log('bar');
}
bar
A recursive function can be defined as: