esra-justBI
1/18/2019 - 2:39 PM

Functions

A resuable block of code that groups together a sequence of statements to perform a specific task.

A function declaration consists of:

  • function keyword
  • name of the function, followed by ()
  • function body, enclosed in {}

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.

  • Declare a variable to make the variable's name be the name of your function. (const)
  • Assign as that variable's value an anonymous function created by function(parameters){}. Functions expression cannot be called before they are defined.

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

  • Functions that take only a single parameter do not need that to be ecnlosed in (). If a function takes 0 or multiple parameters, parentheses are required.
  • Function body composed of a single-line block does not need {}. The concents of that block should immediatley follow => and the return keyword can be removed = implicit return.
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;