Module 5 - Custom Functions

Introduction

JavaScript functions are a fundamental building block of any web application or software written in JavaScript. A function is a self-contained block of code that performs a specific task. It serves as a way to group together a series of statements, giving them a name and allowing you to reuse that code whenever needed. Functions are a powerful tool for organizing your code, making it more readable, and enhancing its reusability.

Why Functions Matter:

Imagine you're building a website, and you need to calculate the total price of items in a shopping cart, validate user input, or display a pop-up message when a button is clicked. These are all tasks that can be achieved using functions. Instead of writing the same code over and over again, you can define a function once and call it whenever you need to perform that specific task.

Functions also promote a structured approach to programming. By breaking down your code into smaller, manageable pieces (functions), you can work on each piece independently, making your code easier to understand, maintain, and collaborate on with others.

In JavaScript, functions are versatile and can be used for a wide range of tasks, from performing complex calculations to interacting with the user interface. As you progress in your JavaScript journey, you'll find that functions are at the core of many web applications, making them a skill worth mastering.

This chapter will walk you through the basics of creating and using functions in JavaScript, starting with the syntax and fundamental concepts. You'll learn how to create functions, pass data to them, and handle the results they produce. By the end of this chapter, you'll have a strong foundation in JavaScript functions and be ready to apply this knowledge to real-world programming challenges.



Function Syntax

JavaScript provides a straightforward syntax for creating functions. A function declaration typically follows this structure:

function functionName() {
// Code to be executed when the function is called
}

Here's an explanation of each component:

function: This keyword tells JavaScript that you're declaring a function.
functionName: This is the name of your function. You can choose a descriptive name that reflects what the function does.
(): The parentheses are used to define any parameters (inputs) the function may require. In this example, there are none.
{}: The curly braces enclose the code block, containing the statements to be executed when the function is called.

Examples with Explanatory Comments:

Let's start with a few basic examples to understand the syntax of function creation:

Example 1: A Simple Greeting Function

function greet() {
console.log("Hello, world!");
}

// Calling the greet function
greet();

In this example, we've created a function called greet. When we call greet(), it logs "Hello, world!" to the console. The function encapsulates this greeting message, making it reusable whenever we want to greet the user.

Example 2: A Function with Parameters

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

const result = add(5, 3);
console.log("The sum is: " + result);

In this example, we've created a function called add that takes two parameters, a and b. It returns the sum of these two values. When we call add(5, 3), it returns 8, and we store that value in the result variable. We then print the result to the console.

Example 3: A Function with Conditional Logic

function isEven(number) {
if (number % 2 === 0) {
return true;
} else {
return false;
}
}

const num = 6;
if (isEven(num)) {
console.log(num + " is even.");
} else {
console.log(num + " is odd.");
}

In this example, we've defined a function called isEven that checks whether a number is even or odd. It takes one parameter, number, and returns true if the number is even and false if it's odd. We call the function with the number 6 and use its result to determine and display whether the number is even or odd.

These examples illustrate the basic syntax and usage of functions in JavaScript. Functions are a key tool in breaking down complex tasks into manageable components, enhancing code reusability, and making your code more organized and readable.



Function Execution

Functions in JavaScript are designed to be executed, or "called," to perform a specific task or set of tasks. In this section, we'll explore how to call functions and see examples of how they execute.

Calling a Function:

To call a function, you use its name followed by parentheses. Here's the basic syntax:

functionName();

When you call a function, the code inside the function is executed, and any specified tasks are performed.

Examples with Explanatory Comments:

Let's look at a few examples to understand how functions are called and executed:

Example 1: Calling a Simple Greeting Function

function greet() {
console.log("Hello, world!");
}

// Calling the greet function
greet();

In this example, we have a function called greet. To execute it, we simply write greet();. When the function is called, it logs "Hello, world!" to the console. The parentheses are used even when the function doesn't have any parameters.

Example 2: Calling a Function with Parameters

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

const result = add(5, 3);
console.log("The sum is: " + result);

In this example, we have a function called add that takes two parameters, a and b. To call this function, we provide the values 5 and 3 as arguments within the parentheses: add(5, 3);. The result of the function call, which is the sum of the provided values, is stored in the result variable.

Example 3: Conditional Function Execution

function isEven(number) {
if (number % 2 === 0) {
return true;
} else {
return false;
}
}

const num = 6;
if (isEven(num)) {
console.log(num + " is even.");
} else {
console.log(num + " is odd.");
}

In this example, we have a function called isEven that checks whether a number is even or odd. To call the function, we pass the number 6 as an argument: isEven(num);. The function returns true, indicating that the number is even, and we use the result in conditional statements to print the appropriate message.

These examples demonstrate how to call functions and execute their code. Functions allow you to encapsulate tasks, making your code more organized and modular. By understanding how to call functions, you can harness their power to perform a wide range of operations in JavaScript.



Return Values

Functions in JavaScript can return values to the code that called them. Return values are a way for functions to produce results that can be used in other parts of your program. In this section, we'll explore how to define return values and how to capture and utilize those values.

Returning Values from Functions:

To return a value from a function, you use the return statement, followed by the value you want to return. Here's the basic syntax:

function functionName() {
// Code within the function
return value;
}

Examples with Explanatory Comments:

Let's examine a few examples to understand how functions return values and how those values can be captured and used:

Example 1: A Simple Addition Function

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

const result = add(5, 3);
console.log("The sum is: " + result);

In this example, we have a function called add that takes two parameters, a and b. The return statement inside the function returns the sum of a and b. When we call add(5, 3);, the function returns the result, which is 8, and we store it in the result variable. Finally, we print the result to the console.

Example 2: A Function with No Return Value

function greet(name) {
console.log("Hello, " + name + "!");
}

greet("Alice");

In this example, the greet function takes a name parameter and logs a greeting message to the console. However, it doesn't have a return statement. When we call greet("Alice");, it doesn't return any value; instead, it performs the console output directly.

Example 3: Using a Return Value in Conditional Statements

function isEven(number) {
if (number % 2 === 0) {
return true;
} else {
return false;
}
}

const num = 6;
if (isEven(num)) {
console.log(num + " is even.");
} else {
console.log(num + " is odd.");
}

In this example, the isEven function checks whether a number is even or odd and returns true or false accordingly. When we call isEven(num);, the function returns true since 6 is even, and we use this return value in conditional statements to print the appropriate message.

These examples illustrate how functions can return values, which can then be captured and used in your code. Return values are valuable for performing calculations, making decisions, and interacting with other parts of your program. Understanding how to work with return values is a fundamental skill in JavaScript programming.



Function Parameters

Function parameters are variables that are used to pass values into a function. They allow functions to accept input data, making them versatile and adaptable to different scenarios. In this section, we'll explore how to define function parameters and how they can be used within functions.

Defining Function Parameters:

To define parameters for a function, you list them inside the parentheses when declaring the function. Here's the basic syntax:

function functionName(parameter1, parameter2, ...) {
// Code within the function can use the parameters
}

Examples with Explanatory Comments:

Let's dive into a few examples to understand how function parameters work and how they are used within functions:

Example 1: A Function with Parameters

function greet(name) {
console.log("Hello, " + name + "!");
}

// Calling the greet function with an argument
greet("Alice");

In this example, we've defined a function called greet that has one parameter, name. When we call the function, such as greet("Alice");, we pass the argument "Alice" to the function. Inside the function, name acts as a variable that holds the value passed as the argument, and it is used to construct the greeting message.

Example 2: A Function with Multiple Parameters

function multiply(a, b) {
return a * b;
}

const result = multiply(5, 3);
console.log("The product is: " + result);

Here, we have a function called multiply with two parameters, a and b. When we call multiply(5, 3);, the values 5 and 3 are passed as arguments to the function. Inside the function, a and b represent these values, and the function returns their product, which is stored in the result variable.

Example 3: Default Parameter Values

function greet(name = "Guest") {
console.log("Hello, " + name + "!");
}

greet(); // Output: "Hello, Guest!"
greet("Alice"); // Output: “Hello, Alice!”

In this example, the greet function has a default parameter value of "Guest". When the function is called without an argument, it uses the default value. If we provide an argument, such as greet("Alice");, it overrides the default value.

Function parameters are a powerful feature in JavaScript, allowing you to create flexible and reusable functions that can accept different inputs. Understanding how to define and work with function parameters is essential for building versatile and dynamic code.



Variable Scope

In JavaScript, variable scope refers to where a variable is accessible and can be used within your code. Understanding function scope is crucial because it determines the visibility and lifetime of variables within functions. In this section, we'll explore the concepts of local and global scope and the idea of variable shadowing.

Local and Global Scope:

Local Scope: Variables declared inside a function are said to have local scope. They are only accessible within that function and cannot be used outside of it. Local variables have a limited lifetime, existing only as long as the function is being executed.

Global Scope: Variables declared outside of any function, at the top level of your script, have global scope. They are accessible from anywhere in your code, including within functions. Global variables have a longer lifetime, persisting as long as the web page is open or the script is running.

Variable Shadowing:

When a variable with the same name is declared both in a local and global scope, the local variable "shadows" the global variable, making it inaccessible within the local scope. This is known as variable shadowing.

Examples with Explanatory Comments:

Let's delve into a few examples to understand local and global scope, as well as variable shadowing:

Example 1: Local and Global Variables

let globalVar = "I'm a global variable";

function exampleFunction() {
let localVar = "I'm a local variable";
console.log(globalVar); // Accessing the global variable
console.log(localVar); // Accessing the local variable
}

exampleFunction();
console.log(globalVar); // Accessing the global variable outside the function
console.log(localVar); // This will result in an error - localVar is not defined

In this example, globalVar is declared as a global variable, while localVar is declared within the exampleFunction. Both variables are accessible within the function, but only globalVar is accessible outside of the function. Attempting to access localVar outside of the function results in an error.

Example 2: Variable Shadowing

let num = 10;

function shadowingExample() {
let num = 20;
console.log("Local num: " + num); // Local variable num is used
}

shadowingExample();
console.log("Global num: " + num); // Global variable num is used

In this example, there is a global variable num, and a local variable num is declared inside the shadowingExample function. When we use num within the function, it refers to the local variable and "shadows" the global variable. Outside of the function, the global variable is accessible.

Understanding variable scope, local and global variables, and variable shadowing is crucial for writing well-organized and error-free JavaScript code. It helps you manage your data effectively and avoid unintended side effects.



Anonymous Functions

In JavaScript, you can define functions without providing a name. These are known as anonymous functions or function expressions. Anonymous functions are often used in situations where a function is needed temporarily, such as when passed as arguments to other functions or when defining event handlers. In this section, we'll explore how to create and use anonymous functions.

Creating Anonymous Functions:

Anonymous functions are created using the function keyword, but they are not assigned a name. They are typically defined within an expression or used immediately in a statement.

Examples with Explanatory Comments:

Let's explore some examples to understand anonymous functions and their common use cases:

Example 1: Anonymous Function as an Argument

const numbers = [1, 2, 3, 4, 5];
// Using the `map` function with an anonymous function
const squaredNumbers = numbers.map(function (num) {
return num * num;
});
console.log(squaredNumbers);

In this example, we have an array of numbers, and we want to square each number using the map function. We provide an anonymous function as an argument to map that defines the squaring operation. The anonymous function is executed for each element in the array, resulting in squaredNumbers.

Example 2: Anonymous Function in Event Handling

const button = document.getElementById("myButton");
button.addEventListener("click", function () {
alert("Button clicked!");
});

Here, we retrieve a button element from the HTML document and attach a click event listener to it. The second argument is an anonymous function that will be executed when the button is clicked. It displays an alert message.

Example 3: Using Arrow Functions

Anonymous functions are often used as arrow functions, which provide a more concise syntax. Here's an example:

const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map((num) => num * num);
console.log(squaredNumbers);

This example is similar to the first one, but it uses an arrow function, a type of anonymous function. Arrow functions are commonly used for shorter, simple functions.

Anonymous functions are a powerful tool in JavaScript, offering flexibility and convenience in various scenarios. They are commonly used when you need a function for a specific task but don't want to define a separate named function. Understanding how to create and utilize anonymous functions is essential for many aspects of modern JavaScript development.



Function Expressions

In JavaScript, function expressions are a way to define functions within an expression, typically without providing a name. Function expressions are often used to create anonymous functions or to define functions dynamically. In this section, we'll explore how to create and use function expressions.

Defining Function Expressions:

Function expressions involve defining a function within an expression and assigning it to a variable. Function expressions can be named or anonymous.

Examples with Explanatory Comments:

Let's delve into a few examples to understand function expressions and their common use cases:

Example 1: Named Function Expression

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

console.log(add(5, 3)); // Using the function expression
// console.log(sum(5, 3)); // This would result in an error

In this example, we define a named function expression called sum and assign it to the variable add. The function sum can only be accessed within the function expression. When we call add(5, 3), it calculates the sum. However, attempting to call sum(5, 3) outside the expression will result in an error.

Example 2: Anonymous Function Expression

const greet = function (name) {
console.log("Hello, " + name + "!");
};

greet("Alice"); // Using the anonymous function expression

In this example, we define an anonymous function expression and assign it to the variable greet. The function is used to greet a person whose name is passed as an argument. The function is executed when we call greet("Alice").

Example 3: Dynamic Function Expression

const operationType = "add";

const operation = operationType === "add" ? function (a, b) {
return a + b;
} : function (a, b) {
return a - b;
};

console.log(operation(5, 3)); // Using the dynamically chosen function

In this example, we use a dynamic function expression to select between addition and subtraction based on the value of operationType. The appropriate function is assigned to the operation variable, which is then used to perform the chosen operation.

Function expressions are valuable for creating functions on-the-fly, especially when the specific function you need depends on dynamic conditions or when you want to keep the function encapsulated within a variable. Understanding how to create and use function expressions is a versatile skill for JavaScript developers.



Callbacks and Higher Order Functions

In JavaScript, functions are first-class citizens, which means they can be passed as arguments to other functions, returned from functions, and assigned to variables. Callback functions and higher-order functions are common concepts that leverage this feature. In this section, we'll explore the use of callback functions and higher-order functions.

Callbacks:

A callback function is a function that is passed as an argument to another function.
The outer function invokes the callback function at a specific point in its execution.
Callbacks are often used to perform tasks after asynchronous operations, such as data retrieval or user interaction, have completed.

Higher-Order Functions:

Higher-order functions are functions that take one or more functions as arguments and may return a function as a result.
They allow for more dynamic and flexible code by enabling the composition of functions and creating reusable patterns.

Examples with Explanatory Comments:

Let's explore some examples to understand the concepts of callback functions and higher-order functions:

Example 1: Basic Callback Function

function greet(name, callback) {
console.log("Hello, " + name + "!");
callback();
}

function farewell() {
console.log("Goodbye!");
}

greet("Alice", farewell);

In this example, the greet function accepts a name and a callback function. It first greets the person, then invokes the callback function, which says goodbye. By passing the farewell function as a callback, we control what happens after the initial greeting.

Example 2: Using a Higher-Order Function

function multiplyBy(factor) {
return function (number) {
return number * factor;
};
}

const double = multiplyBy(2);
const triple = multiplyBy(3);

console.log(double(5)); // Output: 10
console.log(triple(5)); // Output: 15

In this example, the multiplyBy function is a higher-order function that returns a new function. The returned function multiplies a given number by a factor. We create two new functions, double and triple, by calling multiplyBy with different factors and use them to calculate the results of doubling and tripling a number.

Example 3: Using a Higher-Order Function for Filtering

const numbers = [1, 2, 3, 4, 5, 6];

function filterArray(array, condition) {
const filtered = [];
for (const item of array) {
if (condition(item)) {
filtered.push(item);
}
}
return filtered;
}

const evenNumbers = filterArray(numbers, function (number) {
return number % 2 === 0;
});

console.log(evenNumbers); // Output: [2, 4, 6]

In this example, the filterArray function is a higher-order function that filters an array based on a given condition. We use it to filter even numbers from an array by providing a callback function that checks whether a number is even.

Understanding callbacks and higher-order functions is crucial in modern JavaScript development, especially when dealing with asynchronous operations and creating flexible, reusable code. They allow you to write more modular and maintainable code by composing functions and making your code more adaptable to different scenarios.

Videos for Module 5 - Custom Functions

Key Terms for Module 5 - Custom Functions

No terms have been published for this module.

Quiz Yourself - Module 5 - Custom Functions

Test your knowledge of this module by choosing options below. You can keep trying until you get the right answer.

Skip to the Next Question