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:
-
functionNameis 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. -
statementsare 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.
- Single-line and multi-line comments (e.g,
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:
-
Define a function named
countToThree.- Declare a
forloop within the function's body that will perform3iterations. - Execute the
console.logfunction at each iteration of the loop to output the value of theivariable.
- Declare a
-
Execute the
countToThreefunction 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:
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:
-
Define a function named
sayHellothat takes one parameter namedlanguage.- Declare a
switchstatement that takes as argument the value of thelanguageparameter. - Output the string
"Guten Morgen !"if thelanguagevariable equals"de". - Output the string
"Bonjour !"if thelanguagevariable equals"fr". - Output the string
"Good morning!"otherwise.
- Declare a
-
Execute the
sayHellofunction with the string"de"as argument. -
Execute the
sayHellofunction with the string"fr"as argument. -
Execute the
sayHellofunction 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:
function calculatePrice(amount, vat = 20) {
const result = amount + amount * (vat / 100);
console.log(result);
}
calculatePrice(40);
calculatePrice(40, 21.5);
When executed, it will:
-
Define a function named
calculatePricethat takes two parameters namedamountandvat, the latter with a default value of20.- Declare a variable named
resultand initialize it with the value of theamountparameter, plus a percentage calculated from the value of thevatparameter. - Output the value of the
resultvariable.
- Declare a variable named
-
Execute the
calculatePricefunction with the number40as argument. -
Execute the
calculatePricefunction with the numbers40and21.5as 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:
restParametersis the name of the argument.indexis a number representing the position of the argument within the list of supplied arguments, where the first argument starts at position0.
This means that the first argument is accessible through restParameters[0], the second through restParameters[1], and so on.
Notes:
Accessing an invalid
indexwill result in anundefinedvalue.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:
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:
-
Define a function named
sumthat takes as parameter an undetermined list of numbers.- Declare a variable named
totaland initialize it to0, used to store their sum. - Declare a variable name
indexand initialize it0, used to access each element of thenumbersarray. - Declare a
whileloop that will run for as long as the current element in thenumbersarray is notundefined. - Add the value of the current element to the
totalvariable. - Increase the
indexvariable by1. - Output the value of the
totalvariable once there are no more elements.
- Declare a variable named
-
Invoke the
sumfunction with the integer values1,2, and3.
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
undefinedvalue if it doesn't contain areturnstatement: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:
function add(a, b) {
return a + b;
}
const result = add(1, 2);
console.log(result);
When executed, it will:
-
Define a function named
addthat takes two parameters namedaandb.- Return the sum of the
aandbparameters.
- Return the sum of the
-
Declare a variable named
resultand initialize it with the value returned by the execution of theaddfunction. -
Output the value of the
resultvariable.
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
2than can only be divided by1and itself.
Let's consider this script, that implements a function named isPrime() that checks if a number is a prime number:
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:
-
Define a function named
isPrimethat takes as parameter an integer namednumber.- Perform an "early return" and return
falseif the number is lesser or equal to1. - Start a
forloop going from2to the value of thenumberpassed as argument. - Perform an "early return" and return
falseif the remainder of the division of thenumberby the divider equals0. - Otherwise return
true.
- Perform an "early return" and return
-
Invoke the
isPrimefunction with the integer value-2. -
Invoke the
isPrimefunction with the integer value4. -
Invoke the
isPrimefunction with the integer value7.
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