Overview

  • Functions allow you to implement repeatable block of code.
  • Functions are first class objects.
  • Functions are called in order to execute the code within the function.
  • Functions have a variable scope that is local to the function itself.

Standard Functions

javascript
// Basic function that accepts a parameter
function functionName(param) {
  // Do stuff with param
  // optionally return something
}

// Typescript version with type hints
function functionName(param: string) {
  // Do stuff with param
  // optionally return something
}

// Parameters can have default values
function functionName(param1, param2="blah") {
  // Do stuff with params
  // optionally optionally return something
}

// Typescript version with default values
function functionName(param1: string, param2: string="blah") {
  // Do stuff with params
  // optionally return something
}

// Call a function
stuff("things");

Anonymous Functions

Anonymous functions are just functions without a name. They can optionally be assigned to a variable.

javascript
function(param) {
  // Do stuff with param;
  // optionally return something
}

const functionName = function(param) {
  // Do stuff with param;
  // optionally return something
}

Arrow Functions

Arrow functions are a shorthand syntax for anonymous functions.

javascript
(param) => {
  // Do stuff with param;
  // optionally return something
}

// Assign arrow function to variable
const functionName = (param) => {
  // Do stuff with param;
  // optionally return something
}

// If an Arrow function has one statement and returns a value
// it can be written on a single line.
const functionName = (param) => `Say: ${param}`