JavaScript Functions

I. What is a function?

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

II. Declare a function

A function declaration consists of the following:

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

III. 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();

IV. Return a value

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

function add(num1, num2) {
  return num1 + num2;
}

console.log(add(3,4)); // 7

V. Set a default value

We can set a default value for the parameter with the keyword =.

function add(num1 = 1, num2 = 2) {
  return num1 + num2;
}

console.log(add()); // 3

VI. 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));