(When you create a function with a name, that is a function declaration. The name may be omitted in function expressions, making that function “anonymous”.)
Function Declaration:
The function declaration (function statement) defines a function with the specified parameters.
function calcAge1(birthYear) {
return 2037 - birthYear;
}
const age1 = calcAge1(2001);
Function Expression:
The function keyword can be used to define a function inside an expression.
const calcAge2 = function(birthYear) {
return 2037 - birthYear;
}
const age2 = calcAge2(2001);
console.log(age1, age2);
Arrow Functions gives us a way to write functions in much simpler way. To be precise it is another way of writing normal functions.
const calcAge3 = birthYear => 2021 - birthYear;
const age3 = calcAge3(2001);
console.log(age3); // 20
One parameters and multiple statements:
const yearsUntilRetirement = birthYear => {
const age = 2037 - birthYear;
const retirement = 65 - age;
return retirement;
}
console.log(yearsUntilRetirement(1991));
Multiple parameters:
const yearsUntilRetirement = (birthYear, firstName) => {
const age = 2037 - birthYear;
const retirement = 65 - age;
// return retirement;
return `${firstName} retires in ${retirement} years`;
}
console.log(yearsUntilRetirement(1991, "kaarthik"));