JavaScript Functions #
Minimum Viable Example #
As simple as it gets:
function someFunctionName(some_parameter) {
...;
return some_variable_defined_above;
}
// console.log(someFunctionName(argument_of_some_sort))
// ^ does whatever the function says to do to the argument provided for the parameter
^ parameters can be empty.
Function can be called with:
someFunctionName();
Arguments #
Things to know about parameters and their arguments:
-
Order matters
-
Default values can be provided (
function someFunction(some_arg = 'default value') { ... }) -
Functions can take other functions as parameters (see higher order functions).
Helper Functions #
Helper functions: functions called within other functions.
function firstFunction(some_arg) {
...;
return some_var;
}
function secondFunction(another_arg) {
...;
return firstFunction(another_arg);
}
secondFunction(...);
Function Expression #
Related to anonymous functions (function with no name).
Function expression is a mash-up of variables and functions. Convention is to invoke with a const.
const someVar = function(param1, param2) {
...;
return some_value;
}
someVar(arg1, arg2)
Hoisting is not allowed with function expressions (see below for hoisting).
Arrow Functions #
Replace function statement with a fat arrow => to create a function.
Start with parameters.
const some_function = (param1, param2) => {
...;
return some_value;
}
Concise Body Arrow Functions #
A more condensed form of arrow functions.
If there’s just exactly one parameter, () are not required.
const some_var = some_param => {};
If the function body can fit on one line, {} and return are not required.
const some_var = some_param => some_param * some_param; // arbitrary operation in this example
Renaming #
Functions can easily be renamed.
const newName = oldName; // no parentheses
newName(); // just a reference to the original function
Hoisting #
Ability to call a function before it’s defined. Generally not recommended.
someFunctionName();
function someFunctionName(some_arg) {
...;
}
Properties #
.name gets the function’s original name
console.log(someFunction.name)