Updated 8 days ago | GitHub

Functions

What is a Function

A function is a group of lines of code that completes a task. Programmers use functions all the time because they make it easier and faster to code and also make code more readable to other users. Programmers use functions to define procedures in the code (e.g., measure distance, print to the console, find a value, etc.).

A function’s purpose is to execute a set of commands (or lines of code) to complete some procedure. In many cases, we can think of a function as taking in some input or information, doing something, and finally sending back a response or output.

Image depiction of a function taking in input and returning output Source: Wikipedia

Defining a Function

Let’s quickly review the syntax of defining a function.

function functionName(param1, param2) {
  // lines of code
  return; // optional; ends execution. Add an expression (e.g. `return result;`) to send a value back to the caller
}
  • function: This keyword is used to define a function in JavaScript.
  • functionName: This is the name of the function. You should check that the name of the function does not overlap with any variable names to avoid confusion.
  • param1, param2: Functions may take in parameters — named variables that receive values when the function is called. If a function takes in multiple parameters, they must be separated by commas.
  • {}: Curly brackets contain the function body — the statements that run when the function is called.
  • return: The optional return statement ends function execution and specifies the value sent back to the caller. A function with no return statement (or a bare return;) returns undefined.

Calling a Function

Defining a function does not run the code inside it. To actually execute the body, you have to call (or invoke) the function by writing its name followed by a pair of parentheses containing the arguments — the actual values you want to pass to the function’s parameters.

function add(a, b) {
  return a + b;
}

const sum = add(3, 4); // sum is now 7
console.log(sum);

In the example above:

  • a and b are parameters in the function’s definition.
  • 3 and 4 are arguments passed when the function is called.
  • The function returns a + b, so add(3, 4) evaluates to 7, which is stored in sum.

Source: MDN Docs on Functions