How to define a function with input parameters?
function greet(name) {
console.log(`Hello, ${name}!`);
}
How to make a function execute another function (passed as input parameter)?
function execute(executeMe, param) {
console.log("executing the passed function with the given param:");
executeMe(param);
}
// execute the "greet" function that was defined previously:
execute(greet, "World");
How to pass an anonymous function to another function?
execute(function(name) { console.log(`Hello, ${name}!`); }, "World");
// or with an arrow instead of the "function" keyword:
execute((name) => { console.log(`Hello, ${name}!`); }, "World");
How to create aliases for functions?
// invoke the existing function from above:
greet("World");
// create an alias for this function:
const anotherGreet = greet;
// invoke the existing function with an alias:
anotherGreet("World");
How to access function parameters dynamically (without explicitly defining them)?
/**
* You don't have to declare the arguments that you pass into a function.
* Use the "arguments" object to gain access to these anonymous parameters.
*/
function argsAreOkayForMe() {
console.log("the arguments object:");
console.log(arguments);
for (let i = 0; i < arguments.length; i++) {
console.log(`argument ${i}: ${arguments[i]}`);
}
}
How to access function parameters dynamically using "rest parameters"?
/**
* Resembles usage of the implicit arguments object,
* but uses a semi-explicit array with three-dot syntax instead.
*/
function restParameters(...args) {
console.log("an array of arguments:");
console.log(args);
for (let i = 0; i < args.length; i++) {
console.log(`argument ${i}: ${args[i]}`);
}
}
How to define default values for missing parameters?
function defaultParams(first = "first", second) {
console.log(`first: ${first}`);
console.log(`second: ${second}`);
}
defaultParams();
/* output:
first: first
second: undefined
*/