Skip to main content

Function Object in JavaScript – Explained with Examples

A JavaScript function is an executable piece of code used 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 the computer—just like a regular program.

The instructions in a function's body can be a var declaration, return call, console.log() invocation, function definition, or any other JavaScript statements.

note
  • A program is a list of instructions written for a computer to execute.
  • Unlike other object types, you can invoke a function without storing it in a variable.
  • JavaScript's 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. Therefore, eliminating 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.

Below is the syntax of a JavaScript function.

Syntax of a JavaScript Function

function nameOfFunction(parameter1, parameter2, ..., parameterX) {
// function's body
}

As shown in the snippet above, a function is composed of five elements:

  1. A function keyword
  2. The function's name
  3. A list of zero or more parameters
  4. A code block ({...})
  5. The function's body

But what exactly is a parameter, I hear you ask? Let's find out below.

What Is a Parameter?

A parameter specifies the name you wish to call your function's argument.

Keep in mind that 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: A function with two parameters

// 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."

Try it on StackBlitz

Note that JavaScript allows you to set a default parameter value for use-cases when users invoke a function without passing an argument to it.

But how exactly does a default parameter work? Let's find out.

Default Parameters in JavaScript: How Does It Work?

JavaScript's default parameters provide a way to initialize your function's parameter with a default value.

For instance, suppose a user invokes your function without providing a required argument. In such a case, JavaScript will set the parameter's value to undefined.

However, you can use a default parameter to tell JavaScript the default value to use instead of undefined.

Let's see some examples below.

Example 1: A function invoked without a required argument and a 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 one argument to its parameters:
myName("Oluwatobi");

// The invocation above will return:
"My full name is Oluwatobi undefined."

Try it on StackBlitz

The computer automatically set the lastName parameter to undefined because we did not provide a default value.

Now, let's see a second example.

Example 2: A function invoked without a required argument but 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."

Try it on StackBlitz

Instead of undefined, JavaScript used "Sofela" as the lastName parameter's default argument.

Now, let's consider a third example below.

Example 3: A function invoked with undefined as an argument but without a 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."

Try it on StackBlitz

The computer set the lastName parameter to undefined because we provided undefined as myName()'s second argument.

Below is another example.

Example 4: A function invoked with a default parameter and undefined as an argument

// 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."

Try it on StackBlitz

Instead of undefined, JavaScript used "Sofela" as the lastName parameter's default argument.

So, now that we know what a parameter is, we can discuss the body of a function.

What Exactly Is a Function's Body?

A function's body is where you place a sequence of statements that you want to execute.

Here's an example:

function getName() {
const firstName = "Oluwatobi";
const lastName = "Sofela";
console.log(firstName + " " + lastName);
}

Try it on StackBlitz

In the snippet above, the function's body contains three statements that the computer will execute whenever the function gets invoked.

Here's another example:

const bestColors = ["Coral", "Blue", "DeepPink"];

function updateMyBestColors(previousColors, newColor) {
const mybestColors = [...previousColors, newColor];
return mybestColors;
}

updateMyBestColors(bestColors, "GreenYellow");

Try it on StackBlitz

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.

Let's now discuss the typical ways to define a JavaScript function.

How to Define a JavaScript Function

Below are the four typical ways to define a JavaScript function.

  • Function declaration
  • Function expression
  • Arrow function expression
  • Immediately invoking function expression

Let's discuss each definition technique.

Function Declaration in JavaScript

A function declaration is a function created without assigning it to a variable.

note

A function declaration is sometimes called a function definition or function statement.

Here's an example:

function addNumbers() {
return 100 + 20;
}

Try it on StackBlitz

The function above is a function declaration because we defined it without storing it in a variable.

Function Expression in JavaScript

A function expression is a function that you create and assign to a variable.

Here's an example:

const myFuncExpr = function addNumbers() {
return 100 + 20;
};

Try it on StackBlitz

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.

Here's an example:

const myFuncExpr = function() {
return 100 + 20;
};

Try it on StackBlitz

The function above is an anonymous function expression that we assigned to the myFuncExpr variable.

note
  • An anonymous function is a function that has 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.

Arrow Function Expression in JavaScript

An arrow function expression is a shorthand way to write a function expression.

JavaScript's arrow function is defined using a combination of the equality and the greater-than symbols (=>).

Let's see its syntax below.

Syntax of an arrow function

const variableName = () => {
// function's body
}

You can see that we defined the function without a function keyword and a function name.

The omission of a function keyword and a function name is mandatory while writing an arrow function expression. Otherwise, JavaScript will throw a SyntaxError.

Here's an example:

const myFuncExpr = () => {
return 100 + 20;
};

Try it on StackBlitz

Important stuff to know about the JavaScript arrow function expression

Keep these three essential pieces of info in mind whenever you use arrow function expressions.

1. The parameters' parentheses are optional

Suppose your arrow function contains only a single parameter. In such a case, you can omit its parentheses.

Here's an example:

const myFuncExpr = a => {
return a + 20;
};

Try it on CodePen

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 return keyword.

Here's an example:

const myFuncExpr = (x, y) => x + y;

Try it on StackBlitz

In the snippet above, we implicitly returned the sum of parameters x and y by removing the curly brackets and the return keyword.

tip

Whenever you choose to omit the curly brackets, also ensure to 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",
};

Try it on CodeSandbox

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 implicitly return an object literal—without using the return keyword explicitly, ensure to encase the object literal in a grouping operator.

Here's an example:

const myFuncExpr = () => ({
carColor: "White",
shoeColor: "Yellow",
});

Try it on CodeSandbox

Note that you can use the grouping operator to return any single value.

Here's an example:

const myFuncExpr = x => (x + 56);

Try it on CodePen

Let's now discuss another way to define a JavaScript function.

Immediately Invoked Function Expression

An immediately invoked function expression (IIFE) is a function expression that invokes itself automatically.

note

An IIFE is sometimes called a Self-Invoking Function Expression or Self-Executing Anonymous Function Expression.

Syntax of an IIFE

(function() {
/* ... */
})();

As shown in the snippet above, an IIFE is composed of three main components:

  1. A grouping operator: The first pair of parentheses ()
  2. A function: Enclosed within the grouping operator
  3. An invocator: The last pair of parentheses ()

Let's see some examples below.

Example 1: Named IIFE

(function addNumbers() {
console.log(100 + 20);
})();

Try it on StackBlitz

The function in the snippet above is a named self-invoking function expression.

Example 2: Anonymous IIFE

(function() {
console.log(100 + 20);
})();

Try it on StackBlitz

The function in the snippet above is an anonymous self-invoking function expression.

Example 3: Arrow function IIFE

(() => console.log(100 + 20))();

Try it on StackBlitz

The function in the snippet above is an arrow self-invoking function expression.

Example 4: Async IIFE

(async () => console.log(await 100 + 20))();

Try it on StackBlitz

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 a 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"

Try it on CodeSandbox

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 that 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"

Try it on CodeSandbox

The snippet did not return any error because JavaScript evaluated myNum as a number data type.

However, you don't have to assign 4 to a variable before the computer can evaluate its data type appropriately.

You can alternatively encase 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 to a string value:
(4).toString();

// The invocation above will return:
"4"

Try it on CodeSandbox

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.

The use of parentheses to make JavaScript evaluate a 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

Try it on StackBlitz

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

This article discussed what a JavaScript function object is. We also used examples to understand how to define and use it.

Thanks for reading!