Functions
A set of defined functionality that can be called with or with parameters
Using the function keywork
function add(num1, num2) {
return num1 + num2;
}
console.log(add(1,2)); // returns 3
Anonymous functions
The variable becomes the function.
const addUp = function (num1, num2) {
return num1 + num2;
}
console.log(addUp(4,5)); // prints 9
Arrow functions
const result1 = (num1, num2) => {
return num1 + num2;
};
console.log(result1(3,4));
// or
const result2 = (num1, num2) => num1 + num2;
console.log(result2(1,2));
If you do not encapsulate the code after the
=>in{}then you do not have to sayreturn, as this is implied. If you use{}, you must usereturn. ({}is needed if the code is multi-line.)
Optional function values
function hello(firstName, lastName = 'you lamer!') {
return "Hello " + firstName + " " + lastName;
}
console.log(hello("Matt", "P")); // prints Hello Matt P
console.log(hello("Matt")); // prints Hello Matt you lamer
Spread function …
Passes object as parameters to function
function spreadFunction(options = {}) {
const config = { ...options };
console.log(config); // prints object - { a: 'cat', b: 17 }
}
// call with object
spreadFunction({
a: 'cat',
b: 17
});