Functions are one of the most widely-used features in programming. So, it helps to have a solid understanding of how they work.
This tutorial discusses everything you need to know to use JavaScript functions like a pro.
Table of Contents
- What Is a Function?
- Why Functions?
- Syntax of a JavaScript Function
- What Is a
function
Keyword? - What Is a Function Name?
- What Is a Parameter?
- What Is a Code Block?
- What Is a Function Body?
- Types of JavaScript Functions
- What Is a JavaScript Function Declaration?
- What Is a JavaScript Function Expression?
- What Is a JavaScript Arrow Function Expression?
- What Is a JavaScript Immediately Invoked Function Expression?
- Overview
So, let's get started from the basics.
What Is a Function?
A JavaScript function is an executable piece of code developers use to bundle a block of zero or more statements.
In other words, a function is an executable subprogram (mini-program).
A JavaScript function is a subprogram because its body consists of a series of statements (instructions) to computers—just like a regular program.
The instructions in a function's body can be a variable declaration, return call, console.log() invocation, function definition, or any other JavaScript statements.
Note:
- A program is a list of instructions written for computers to execute.
- Unlike other object types, you can invoke a function without storing it in a variable.
- A JavaScript function is similar to other programming languages' procedures or subroutines.
Why Functions?
Functions provide a way to bundle pieces of code together and reuse them anytime, anywhere, for an unlimited period. This helps you eliminate the burden of writing the same set of code repeatedly.
For instance, alert() is a built-in window function that someone wrote once for all developers to use anytime, anywhere.
Syntax of a JavaScript Function
function nameOfFunction(parameter1, parameter2, ..., parameterX) {
// function's body
}
A function is composed of five elements:
- A
function
keyword - The function's name
- A list of zero or more parameters
- A code block (
{...}
) - The function's body
Let's discuss each element.
What Is a function
Keyword?
We use the function
keyword to declare to browsers that a specific piece of code is a JavaScript function—not a mathematical or other generic function.
What Is a Function Name?
A function's name allows you to create an identifier for your function, which you can use to reference it.
What Is a Parameter?
A parameter specifies the name you wish to call your function's argument.
A parameter is an optional component of a function. In other words, you do not need to specify a parameter if your function does not accept any argument.
For instance, JavaScript's pop() method is a function without any parameter because it does not accept arguments.
On the other hand, forEach() has two parameters that accept two arguments.
Example of a JavaScript parameter
// Define a function with two parameters:
function myName(firstName, lastName) {
console.log(`My full name is ${firstName} ${lastName}.`);
}
// Invoke myName function while passing two arguments to its parameters:
myName("Oluwatobi", "Sofela");
// The invocation above will return:
"My full name is Oluwatobi Sofela."
The myName()
function in the snippet above has two parameters: firstName
and lastName
.
Suppose you wish to pre-define values for your parameters that browsers can use if users do not invoke the function with the required arguments. In that case, you can create default parameters.
What is a default parameter?
Default parameters allow you to initialize your function's parameters with default values.
For instance, suppose users invoke your function without providing a required argument. In such a case, browsers will set the parameter's value to undefined
.
However, default parameters allow you to define the values browsers should use instead of undefined
.
Examples of default parameters
Below are examples of how default parameters work in JavaScript.
How to define a function with no default parameters
// Define a function with two parameters:
function myName(firstName, lastName) {
console.log(`My full name is ${firstName} ${lastName}.`);
}
// Invoke myName function while passing one argument to its parameters:
myName("Oluwatobi");
// The invocation above will return:
"My full name is Oluwatobi undefined."
The computer automatically set the lastName
parameter to undefined
because we did not provide a default value.
How to define a function with an undefined
argument and no default parameter
// Define a function with two parameters:
function myName(firstName, lastName) {
console.log(`My full name is ${firstName} ${lastName}.`);
}
// Invoke myName function while passing two arguments to its parameters:
myName("Oluwatobi", undefined);
// The invocation above will return:
"My full name is Oluwatobi undefined."
The computer set the lastName
parameter to undefined
because we provided undefined
as myName()
's second argument.
How to define a function with a default parameter
// Define a function with two parameters:
function myName(firstName, lastName = "Sofela") {
console.log(`My full name is ${firstName} ${lastName}.`);
}
// Invoke myName function while passing one argument to its parameters:
myName("Oluwatobi");
// The invocation above will return:
"My full name is Oluwatobi Sofela."
Instead of undefined
, JavaScript used "Sofela"
as the lastName
parameter's default argument.
How to define a function with an undefined
argument and a default parameter
// Define a function with two parameters:
function myName(firstName, lastName = "Sofela") {
console.log(`My full name is ${firstName} ${lastName}.`);
}
// Invoke myName function while passing two arguments to its parameters:
myName("Oluwatobi", undefined);
// The invocation above will return:
"My full name is Oluwatobi Sofela."
Instead of undefined
, JavaScript used "Sofela"
as the lastName
parameter's default argument.
Let's now discuss the fourth element of a JavaScript function: a code block.
What Is a Code Block?
A block is a pair of braces ({...}
) used to group multiple statements together.
Here's an example:
{
const hourNow = new Date().getHours();
}
The block in the snippet above encased one JavaScript statement.
Here's another example:
if (new Date().getHours() < 18) {
const hourNow = new Date().getHours();
const minutesNow = new Date().getMinutes();
console.log(`The time is ${hourNow}:${minutesNow}.`);
}
The if
condition's code block grouped three JavaScript statements together.
Now, consider this snippet:
function getTime() {
const hourNow = new Date().getHours();
const minutesNow = new Date().getMinutes();
console.log(`The time is ${hourNow}:${minutesNow}.`);
}
The getTime()
function's code block grouped three JavaScript statements. Note that the "function body" is the space inside the function's code block. Let's talk more about it now.
What Is a Function Body?
A function body is where you place a sequence of statements you want to execute.
Syntax of a JavaScript function body
function nameOfFunction() {
// function's body
}
Function body examples
Below are examples of how we use the function body.
How to define a function with three statements in its body
function getName() {
const firstName = "Oluwatobi";
const lastName = "Sofela";
console.log(firstName + " " + lastName);
}
In the snippet above, the function's body contains three statements that the computer will execute whenever the function gets invoked.
Note: console.log()
is a method we use to log (write) messages to a web console.
How to define a function with two statements in its body
const bestColors = ["Coral", "Blue", "DeepPink"];
function updateMyBestColors(previousColors, newColor) {
const mybestColors = [...previousColors, newColor];
return mybestColors;
}
updateMyBestColors(bestColors, "GreenYellow");
In the snippet above, the function's body contains two statements that the computer will execute whenever the function gets invoked.
Note:
- The three dots we prepended to
previousColors
is called a spread operator. We used it to expand the array argument into individual elements. - You can also prepend the
newColor
parameter with a rest operator if you wish to add two or more new colors. - The
return
keyword ends its function's execution and returns the specified expression (orundefined
if you provide no expression).
So, now that we know the components of a JavaScript function, we can discuss its types.
Types of JavaScript Functions
The four types of JavaScript functions are:
- Function declaration
- Function expression
- Arrow function expression
- Immediately invoking function expression
Let's discuss each type.
What Is a JavaScript Function Declaration?
A function declaration is a function created without assigning it to a variable.
Note: We sometimes call function declaration a "function definition" or "function statement."
Here's an example:
function addNumbers() {
return 100 + 20;
}
The function above is a function declaration because we defined it without storing it in a variable.
What Is a JavaScript Function Expression?
A function expression is a function you create and assign to a variable.
Here's an example:
const myFuncExpr = function addNumbers() {
return 100 + 20;
};
The function above is a named function expression that we assigned to the myFuncExpr
variable.
You can also write the snippet above as an anonymous function expression like so:
const myFuncExpr = function() {
return 100 + 20;
};
The function above is an anonymous function expression that we assigned to the myFuncExpr
variable.
Note:
- An anonymous function is a function with no name.
- A named function is a function with a name.
A named function's main advantage is that the name makes it easier to trace an error's origin.
In other words, suppose your function threw an error. In such a case, if the function is named, a debugger's stack trace will contain the function's name. Therefore, you will find it easier to identify the error's origin.
What Is a JavaScript Arrow Function Expression?
An arrow function expression is a shorthand way to write a function expression.
Syntax of an arrow function
We define an arrow function with the equality and the greater-than symbols (=>
). Here is the syntax:
const variableName = () => {
// function's body
}
Example of an arrow function
const myFuncExpr = () => {
return 100 + 20;
};
You can see that we defined the function without a function
keyword and a function name.
You have to omit the function
keyword and function name while writing an arrow function expression. Otherwise, JavaScript will throw a SyntaxError
.
Important stuff to know about the JavaScript arrow function expression
Here are three essential facts to remember when using an arrow function expression.
1. The parameters' parentheses are optional
Suppose your arrow function contains only a single parameter. In such a case, you can omit its parentheses.
const myFuncExpr = a => {
return a + 20;
};
2. The curly brackets and return
keyword are optional
Suppose your arrow function contains only a single statement. In that case, you can omit its curly brackets and the return
keyword.
const myFuncExpr = (x, y) => x + y;
In the snippet above, we implicitly returned the sum of parameters x
and y
by removing the curly brackets and the return
keyword.
Note: Whenever you choose to omit the curly brackets, also make sure that you remove the return
keyword. Otherwise, the computer will throw a SyntaxError
.
3. Use parentheses to wrap any implicit object return
Suppose you wish to return an object implicitly. In such a case, wrap the object in a grouping operator (...)
.
For instance, consider the code below:
const myFuncExpr = () => {
carColor: "White",
shoeColor: "Yellow",
};
The snippet above will throw a SyntaxError
because JavaScript assumed the curly brackets ({}
) to be the function body's code block—not an object literal.
Therefore, whenever you wish to return an object literal implicitly–without using the return
keyword explicitly–make sure to encase the object literal in a grouping operator.
Here's an example:
const myFuncExpr = () => ({
carColor: "White",
shoeColor: "Yellow",
});
Note that you can use the grouping operator to return any single value. For instance, the snippet below grouped the sum of x
and 56
.
const myFuncExpr = x => (x + 56);
Let's now discuss the fourth type of JavaScript function.
What Is a JavaScript Immediately Invoked Function Expression?
An immediately invoked function expression (IIFE) is a function expression that invokes itself automatically.
Note: We sometimes call an IIFE a "Self-Invoking Function Expression" or "Self-Executing Anonymous Function Expression."
Syntax of an IIFE
(function() {
/* ... */
})();
An IIFE is composed of three main components:
- A grouping operator: The first pair of parentheses
()
- A function: Enclosed within the grouping operator
- An invocator: The last pair of parentheses
()
Examples
Below are examples of an IIFE.
How to define a named IIFE
(function addNumbers() {
console.log(100 + 20);
})();
The function in the snippet above is a named self-invoking function expression.
How to define an anonymous IIFE
(function() {
console.log(100 + 20);
})();
The function in the snippet above is an anonymous self-invoking function expression.
How to define an arrow function IIFE
(() => console.log(100 + 20))();
The function in the snippet above is an arrow self-invoking function expression.
How to define an async IIFE
(async () => console.log(await 100 + 20))();
The function in the snippet above is an asynchronous self-invoking function expression.
So, now that we know what an Immediately Invoked Function Expression is, we can discuss how it works.
How does an IIFE work?
By default, the computer does not know what data type code is until it evaluates it.
For instance, suppose you ask the computer to process 4
. In such a case, the system won't know if 4
is a number type until it evaluates it.
Therefore, JavaScript will throw a SyntaxError
if you use any number method directly on 4
.
Here's an example:
// Convert 4 to a string value:
4.toString();
// The invocation above will return:
"Uncaught SyntaxError: Invalid or unexpected token"
The computer threw a SyntaxError
because it does not recognize 4
as a number data type.
However, suppose you assign 4
to a variable. In such a case, the computer will first convert it to a number data type before storing it into the variable.
Afterward, JavaScript will allow you to use any number methods on the number variable.
Here's an example:
// Assign 4 to a variable:
const myNum = 4;
// Convert myNum's content to a string value:
myNum.toString();
// The invocation above will return:
"4"
The snippet above did not return any error because JavaScript evaluated myNum
as a number data type.
But you don't have to assign 4
to a variable before the computer can evaluate its data type appropriately.
You can alternatively put your value in parentheses to force the computer to evaluate its data type before using it for other things.
For instance, consider this snippet:
// Evaluate 4's data type and turn it into a string value:
(4).toString();
// The invocation above will return:
"4"
The snippet above enclosed 4
in parentheses to make the computer evaluate its data type before using the toString()
method to convert it to a string value.
Using parentheses to make JavaScript evaluate your code's data type first is what happens in an Immediately Invoking Function Expression (IIFE).
For instance, consider this example:
// Evaluate the function's data type and immediately invoke it:
(function addNumbers() {
console.log(100 + 20);
})();
// The invocation above will return:
120
The snippet above enclosed the addNumbers
function in parentheses to make the computer evaluate its data type before invoking it immediately after the evaluation.
Overview
In this article, we discussed what a JavaScript function object is. We also used examples to see how it works.
Thanks for reading.
And here's a useful ReactJS resource:
I wrote a book about React!
- It's beginner friendly ✔
- It has live code snippets ✔
- It contains scalable projects ✔
- It has plenty of easy-to-grasp examples ✔
The React Explained Clearly book is all you need to understand ReactJS.