Reuse Code With Functions in JavaScript

20 min read·Jan 1, 2026

In JavaScript, a function is a reusable code structure that allows you to encapsulate a set of related statements in order to perform a specific task.

Functions allow you to easily reuse and execute these statements multiple times from various parts of a script, without having to manually repeat them.

💡 Note that executing, calling, running, and invoking a function essentially mean the same thing and are often used interchangeably.

Declare and execute functions

In JavaScript, functions are declared using the function keyword:

function functionName() {
  statements
}

Where:

  • functionName is the name of the function.

  • () are delimiters used to list function parameters.

  • {} are delimiters used to encapsulate the function's statements, also called the body.

  • statements are a set of statements, including but not limited to:

    • Single-line and multi-line comments (e.g, //, /**/).
    • Variable declaration and assignment (e.g., let, =).
    • Control statements (e.g., if, else).
    • Loops (e.g., for, while).
    • Logical operators (e.g., &&, ==).
    • Function calls (e.g., console.log).
    • Etc.

Once declared, functions can be invoked multiple times from anywhere in the script, including other functions, using their name followed by parenthesis ():

functionName();

💡 Tip: You should always declare all variables and functions at the top of their scope before actually using them!

Example

Let's consider this script, that implements a function named countToThree() that outputs all numbers from 1 to 3:

function countToThree() {
  for (let i = 1 ; i <= 3 ; i++) {
    console.log(i);
  }
}

countToThree();

When executed, it will:

  1. Define a function named countToThree.

    • Declare a for loop within the function's body that will perform 3 iterations.
    • Execute the console.log function at each iteration of the loop to output the value of the i variable.
  2. Execute the countToThree function once.

Which will produce this output:

1
2
3

Define function parameters

Function parameters, also called named parameters, are named variables defined in a function's signature, between the parenthesis ().

They allow functions to receive and use arbitrary values, such as strings, numbers, arrays, objects, and so on.

function functionName(parameter1, parameter2, ..., parameterN) {
  //
}

These values, then referred to as arguments, are supplied when the function is invoked and are assigned to each parameter in their order of declaration.

functionName(value1, value2, ..., valueN);

This means that, upon execution, value1 will be assigned to parameter1, value2 will be assigned to parameter2, and so on.

Example

Let's consider this script, that implements a function named sayHello() that dynamically outputs the sentence "Good morning" in various languages:

say_hello.js
function sayHello(language) {
  switch (language) {
    case 'de':
      console.log('Guten Morgen !');
      break;
    case 'fr':
      console.log('Bonjour !');
      break;
    default:
      console.log('Good morning!');
      break;
  }
}

sayHello('de');
sayHello('fr');
sayHello();

When executed, it will:

  1. Define a function named sayHello that takes one parameter named language.

    • Declare a switch statement that takes as argument the value of the language parameter.
    • Output the string "Guten Morgen !" if the language variable equals "de".
    • Output the string "Bonjour !" if the language variable equals "fr".
    • Output the string "Good morning!" otherwise.
  2. Execute the sayHello function with the string "de" as argument.

  3. Execute the sayHello function with the string "fr" as argument.

  4. Execute the sayHello function with no argument.

Which will produce this output:

$ node say_hello.js
Guten Morgen !
Bonjour !
Good morning!

Default function parameters

Default parameters are named parameters defined with a default value that provide a way to handle missing or undefined arguments.

function functionName(parameter = defaultValue) {
  //
}

Example

Let's consider this script, that implements a function named calculatePrice() that outputs a price including VAT:

calculate_price.js
function calculatePrice(amount, vat = 20) {
  const result = amount + amount * (vat / 100);

  console.log(result);
}

calculatePrice(40);
calculatePrice(40, 21.5);

When executed, it will:

  1. Define a function named calculatePrice that takes two parameters named amount and vat, the latter with a default value of 20.

    • Declare a variable named result and initialize it with the value of the amount parameter, plus a percentage calculated from the value of the vat parameter.
    • Output the value of the result variable.
  2. Execute the calculatePrice function with the number 40 as argument.

  3. Execute the calculatePrice function with the numbers 40 and 21.5 as arguments.

Which will produce this output:

$ node calculate_price.js
48
48.6

Rest function parameters

Unlike named parameters, the rest parameter syntax allows functions to accept an undetermined number of arguments as a unique array (or list) of values.

function functionName(...restParameters) {
  //
}

From within the function's body, the value of each parameter is accessible using this syntax:

restParameters[index]

Where:

  • restParameters is the name of the argument.
  • index is a number representing the position of the argument within the list of supplied arguments, where the first argument starts at position 0.

This means that the first argument is accessible through restParameters[0], the second through restParameters[1], and so on.

Notes:

  • Accessing an invalid index will result in an undefined value.

  • When combined with named parameters, rest parameters must be declared last.

    function functionName(parameter1, parameter2, ...restParameters) {
      //
    }
    

Example

Let's consider this script, that implements a function named sum() that outputs the sum of an undetermined number of integers:

sum.js
function sum(...numbers) {
  let total = 0;
  let index = 0;

  while (numbers[index] !== undefined) {
    total += numbers[index];
    index++;
  }
  console.log(total);
}

sum(1, 2, 3);

When executed, it will:

  1. Define a function named sum that takes as parameter an undetermined list of numbers.

    • Declare a variable named total and initialize it to 0, used to store their sum.
    • Declare a variable name index and initialize it 0, used to access each element of the numbers array.
    • Declare a while loop that will run for as long as the current element in the numbers array is not undefined.
    • Add the value of the current element to the total variable.
    • Increase the index variable by 1.
    • Output the value of the total variable once there are no more elements.
  2. Invoke the sum function with the integer values 1, 2, and 3.

Which will produce this output:

$ node sum.js
6

Send a return value

In JavaScript, the return value refers to the value sent by a function back to the calling code when it completes its execution.

This value is sent using the return statement, which when encountered, immediately terminates the function's execution.

function functionName() {
  return expression;
}

The return value can then be captured into a variable using the assignment operator =.

let variable = functionName();

Or directly passed as argument of another function:

functionA(functionB());

Note: By default, a function will return an undefined value if it doesn't contain a return statement:

function functionName() {
  //
}

Or if the return value is omitted.

function functionName() {
  return;
}

Example

Let's consider this script, that implements a function named add() that returns the sum of two numbers:

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

const result = add(1, 2);

console.log(result);

When executed, it will:

  1. Define a function named add that takes two parameters named a and b.

    • Return the sum of the a and b parameters.
  2. Declare a variable named result and initialize it with the value returned by the execution of the add function.

  3. Output the value of the result variable.

Which will produce this output:

$ node add.js
3

Perform an early return

An "early return" refers to the practice of terminating a function prematurely by using a return statement before reaching the end of the function's body.

It typically involves placing a return statement within a conditional statement to exit the function if a certain condition is met, therefore avoiding unnecessary execution of subsequent code.

It helps avoid deeply nested logic, thus enhancing code readability and maintainability.

Example

📚 Definition: A prime number is a positive integer greater or equal to 2 than can only be divided by 1 and itself.

Let's consider this script, that implements a function named isPrime() that checks if a number is a prime number:

is_prime.js
function isPrime(number) {
  if (number <= 1) {
    console.log(number + ' is lesser than or equal to 1');
    return false;
  }

  for (let divider = 2 ; divider < number ; divider++) {
    if (number % divider == 0) {
      console.log(number + ' is divisible by ' + divider);
      return false;
    }
  }

  console.log(number + ' is prime');
  return true;
}

console.log(isPrime(-2));
console.log(isPrime(4));
console.log(isPrime(7));

When executed, it will:

  1. Define a function named isPrime that takes as parameter an integer named number.

    • Perform an "early return" and return false if the number is lesser or equal to 1.
    • Start a for loop going from 2 to the value of the number passed as argument.
    • Perform an "early return" and return false if the remainder of the division of the number by the divider equals 0.
    • Otherwise return true.
  2. Invoke the isPrime function with the integer value -2.

  3. Invoke the isPrime function with the integer value 4.

  4. Invoke the isPrime function with the integer value 7.

Which will produce this output:

$ node is_prime.js
-2 is lesser than or equal to 1
false
4 is divisible by 2
false
7 is prime
true

Enjoying the courses?

I've made these courses completely free so anyone can learn from them. If they've helped you and you'd like to actively support the work behind BackendBrewery, you can leave a tip:

Support BackendBrewery
Reuse Code With Functions in JavaScript | Backend Brewery