A resuable block of code that groups together a sequence of statements to perform a specific task.
A function declaration consists of:
Hoisting: allows access to function declarations before they're defined. But it isn't ocnsidered good practice.
Function executes only when the function is called. To call it, use the function name followed by ().
Parameters allow functions to accept input(s) and preform a task using the inputs. We use parameters as placeholders for info that will be passed to the function when it is called. We specify the values in the () that follow the function name. They are called arguments. Can be passed as values or variables.
Default parameter = predetermined value in case no argument passed into the function, or if the argument is undefined when called.
Return statement = pass back info from the function call. If the value is omitted, undefined is returned instead. When the return is used, the execution of the function is stopped and the code that follows it will not be executed. It allows functions to produce an output. We can save this output to a variable for later use.
Helper function = use the return value of a function inside another function. Makes it easier to read & debug.
Function expressions = define a function inside an expression. A function with no name = anonymous function. Is often stored in a variable in order to refer to it.
Arrow functions = a shorter way to write function by using () => notation. They remove the need to type out the keyword function every time you create a function.
Concise body arrow functions
Function with parameters
function calculateArea(width, height) {
console.log(width * height)'
}
//Helper functions
function multiplyByNineFifths(number) {
return number * (9/5);
};
function getFahrenheit(celsius) {
return multiplyByNineFifths(celsius) + 32;
};
getFahrenheit(15); // Returns 59
// Arrow functions
const rectangleArea = (width, height) => {
let area = width * height;
return area
}
const squareNum = (num) => {
return num * num;
};
We can refactor the function to:
const squareNum = num => num * num;