Functions

I. What is a function?

A function is a reusable block of code that groups together a sequence of statements to perform a specific task.

1. Declare a function

A function declaration consists of:

  • The function keyword.
  • The name of the function
  • Some functions can take inputs (parameters) and use them to perform a task
  • A function body
function name(parameter1, parameter2, parameter3) {
  // code to be executed
}

2. Call a function

To call a function in your code, you type the function name followed by parentheses.

For example

function hello() {
    console.log('Hello');
}

hello();

3. Return a value

To return a value from a function, we use a return statement.

II. Arrow function

ES6 introduced arrow function syntax. Arrow functions remove the need to type out the keyword function every time you need to create a function.

const plantNeedsWater = function(day) {
  if (day === 'Wednesday') {
    return true;
  } else {
    return false;
  }
};

similar to

const plantNeedsWater = (day) => {
  if (day === 'Wednesday') {
    return true;
  } else {
    return false;
  }
};

Rules

  1. Functions that take only a single parameter do not need that parameter to be enclosed in parentheses. However, if a function takes zero or multiple parameters, parentheses are required.
// Zero parameters
const functionName = () => {};

// 1 parameter
const functionName = para1 => {};

// 2 parameters
const functionName = (para1, para2) => {};
  1. A function body with a single-line block does not need curly braces.
// Single-line block
const multiNumbers = number => number * number;

// Multi-line block
const multiNumbers = number => {
    const multi = number * number;
    return multi; 
}

III. Set default parameters for functions

We can set default value for parameter with keyword =

const add = (function() {
  return function add(number, value = 1) {
    return number + value;
  };
})();
console.log(add(3, 2)); //5
console.log(add(3));    // 4

IV. Rest Operator with Function Parameters

The rest parameter allows us to represent an indefinite number of arguments as an array.

const sum = (function() {
  return function sum(...args) {
    return args.reduce((a, b) => a + b, 0);
  };
})();
console.log(sum(1, 2, 3));

is similar to

const sum = (function() {
  return function sum(x, y, z) {
    const args = [ x, y, z ];
    return args.reduce((a, b) => a + b, 0);
  };
})();
console.log(sum(1, 2, 3));