Back to Web Development
2026-03-187 min read

Test: Functions (Web Development)

Learn Test: Functions (Web Development) step by step with clear examples and exercises.

Why This Matters

Functions are the building blocks of efficient and maintainable web development. By learning how to create, use, and manage functions effectively, you'll be able to write cleaner, more organized code that is easier to debug, optimize, and understand. Mastering functions will help you tackle complex coding challenges, improve your productivity, and prepare for job interviews in the field of web development.

Prerequisites

Before diving into functions, it's crucial to have a strong foundation in the following areas:

  1. Basic HTML syntax and structure
  2. CSS styling basics
  3. JavaScript fundamentals, including variables, data types, operators, control structures (if/else statements), and loops
  4. Understanding of the Document Object Model (DOM) and how to manipulate it using JavaScript

Core Concept

Definition

A function is a reusable piece of code that performs a specific task or calculates a value. Functions allow you to group related statements together, making your code more modular, easier to manage, and less error-prone. In JavaScript, functions are defined using the function keyword followed by the name of the function, parentheses (), and curly braces {}.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Functions Example</title>
</head>
<body>
<script>
// Define a function called greet that takes one parameter (name) and logs a greeting message
function greet(name) {
console.log(`Hello, ${name}!`);
}

// Call the function with an argument (John Doe)
greet("John Doe"); // Output: Hello, John Doe!

// Define another function called add that takes two parameters (num1 and num2) and returns their sum
function add(num1, num2) {
const sum = num1 + num2;
return sum;
}

// Call the function with arguments (5 and 3) and store the result in a variable
const result = add(5, 3);

// Log the result to the console
console.log(result); // Output: 8
</script>
</body>
</html>

Function Parameters and Return Values

Functions can take input through parameters and return output as a value. To define function parameters, simply list them within the parentheses when defining the function. To return a value from a function, use the return keyword followed by the value you want to send back.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Functions Example</title>
</head>
<body>
<script>
// Define a function called square that takes one parameter (num) and returns its square
function square(num) {
return num * num;
}

// Call the function with an argument (4) and store the result in a variable
const result = square(4);

// Log the result to the console
console.log(result); // Output: 16
</script>
</body>
</html>

Anonymous Functions (Arrow Functions)

In addition to named functions, JavaScript also supports anonymous functions, often referred to as arrow functions. Arrow functions are a more concise syntax for writing functions without the need to explicitly define a name. They can be defined using the => operator instead of traditional curly braces and the keyword function.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Functions Example</title>
</head>
<body>
<script>
// Define an anonymous function (arrow function) that takes a single argument (num) and returns its square
const squareArrow = num => num * num;

// Call the function with an argument (4) and store the result in a variable
const result = squareArrow(4);

// Log the result to the console
console.log(result); // Output: 16
</script>
</body>
</html>

Worked Example

Create a simple web page that allows users to enter their name, age, and gender (male or female), calculates their Body Mass Index (BMI) based on their weight and height, and displays an appropriate message.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Body Mass Index Calculator</title>
</head>
<body>
<h1>Body Mass Index (BMI) Calculator</h1>

<!-- Form to collect user input -->
<form id="bmiForm">
Name: <input type="text" name="name" required><br>
Age: <input type="number" name="age" min="0" max="120" required><br>
Gender:
<select name="gender" id="gender" required>
<option value="male">Male</option>
<option value="female">Female</option>
</select><br>
Weight (kg): <input type="number" step="0.1" name="weight" min="10" max="250" required><br>
Height (m): <input type="number" step="0.01" name="height" min="1" max="3" required><br>
<button type="submit">Calculate BMI</button>
</form>

<!-- Output element for displaying the result -->
<div id="result"></div>

<script>
// Define a function to calculate Body Mass Index (BMI) based on weight and height
function calculateBMI(weight, height) {
const bmi = weight / Math.pow(height, 2);
return bmi;
}

// Define a function to determine the BMI category based on the calculated value
function determineCategory(bmi) {
if (bmi < 18.5) {
return "Underweight";
} else if (bmi >= 18.5 && bmi <= 24.9) {
return "Normal weight";
} else if (bmi >= 25 && bmi <= 29.9) {
return "Overweight";
} else {
return "Obese";
}
}

// Add an event listener for the form submission
document.getElementById("bmiForm").addEventListener("submit", function(event) {
event.preventDefault(); // Prevent the page from refreshing upon form submission

const name = document.querySelector("#bmiForm input[name='name']").value;
const age = parseInt(document.querySelector("#bmiForm input[name='age']").value);
const gender = document.querySelector("#bmiForm select[name='gender']").value;
const weight = parseFloat(document.querySelector("#bmiForm input[name='weight']").value);
const height = parseFloat(document.querySelector("#bmiForm input[name='height']").value);

// Calculate BMI and determine the category
const bmi = calculateBMI(weight, height);
const category = determineCategory(bmi);

// Log the result to the console for demonstration purposes
console.log(`${name} (${age}, ${gender}) has a BMI of ${bmi}. Their category is ${category}.`);

// Display the result in the output element
document.getElementById("result").textContent = `${name}: Your BMI is ${bmi}. Your category is ${category}.`;
});
</script>
</body>
</html>

Common Mistakes

  1. Forgetting to define the function before calling it: Make sure to define your functions before using them in your code.
  2. Not passing the correct number or type of arguments: Ensure that you are passing the correct number and type of arguments when calling a function, as defined in its parameters.
  3. Ignoring return values: Don't forget to handle the return value of a function if necessary. Assign it to a variable or use it directly in your code.
  4. Not using proper syntax for arrow functions: Remember that arrow functions should be defined using the => operator instead of traditional curly braces and the keyword function.
  5. Not handling errors: Learn how to handle errors effectively by using try/catch blocks or other error-handling techniques.
  6. Overcomplicating functions: Try to keep your functions simple, focused on a single task, and easy to understand. Avoid nesting too many functions within each other.
  7. Not optimizing function performance: Be aware of potential performance issues when using recursive functions or large loops inside functions. Consider using more efficient algorithms or data structures where possible.
  8. Not documenting your functions: Properly documenting your functions with comments and clear names can help others understand your code more easily.

Practice Questions

  1. Write a JavaScript function that calculates the factorial of a number (n! = n \ (n - 1) \ ... \* 1). Test your function with an example input of 5.
  2. Create a JavaScript function that takes two parameters, num1 and num2, and returns their sum, difference, product, quotient, and the maximum of the two numbers. Test your function with the following inputs: (3, 7) and (-4, 9).
  3. Write an arrow function in JavaScript that filters an array of numbers to only include odd numbers. Test your function with the following input: [1, 2, 3, 4, 5, 6, 7, 8, 9].
  4. Write a recursive JavaScript function that calculates the Fibonacci sequence up to the nth term (where n is a given number). Test your function with an example input of 10.
  5. Create a JavaScript function that takes an array of numbers and sorts it in ascending order using the bubble sort algorithm. Test your function with the following input: [5, 2, 8, 7, 3].
  6. Write a JavaScript function that finds the first non-repeating character in a given string. Test your function with the example string "listen".

FAQ

Q: Can I pass a function as an argument to another function in JavaScript?

A: Yes! This is known as higher-order functions and allows you to build more flexible, reusable code.

Q: What happens if I don't return anything from a JavaScript function?

A: If a JavaScript function doesn't explicitly return a value, it implicitly returns undefined.

Q: Is it possible to define a recursive function in JavaScript?

A: Yes! Recursion is a powerful technique for solving complex problems by breaking them down into smaller, more manageable parts.

Q: How do I handle multiple return values from a JavaScript function?

A: You can use an array or object to store and return multiple values from a JavaScript function. Alternatively, you can define multiple functions within the same block and call them as needed.

Q: How can I optimize the performance of my recursive functions in JavaScript?

A: To optimize the performance of your recursive functions, consider using memoization or tail recursion to reduce the number of function calls and improve efficiency.

Q: What are some best practices for writing clean, maintainable functions in JavaScript?

A: Some best practices include keeping functions small and focused, using descriptive names, documenting your code with comments, and following a consistent coding style. Additionally, consider using linting tools to enforce code quality and consistency across your project.

Test: Functions (Web Development) | Web Development | XQA Learn