14.5 Best Practices for Functions (10 mins)

  1. Naming Conventions for Functions:

    • Clear and Descriptive Names: Function names should clearly describe what the function does, making the code easy to read and understand.

      • Good Example: calculateTotalPrice()

      • Bad Example: calc()

    • Verb-Noun Structure: Function names should usually start with a verb followed by a noun to indicate the action the function performs.

      • Common verbs: get, set, calculate, fetch, update, validate

      • Example: getUserData(), validateForm()

  2. Reusability:

    • Write Reusable Functions: Functions should be written in a way that they can be reused in different parts of the application. Avoid hardcoding values inside functions. Instead, pass values through parameters.

      • Example:

        // Reusable function to calculate area of a rectangle
        function calculateArea(length, width) {
          return length * width;
        }
        let area1 = calculateArea(10, 5);
        let area2 = calculateArea(7, 3);  // Function can be reused with different values
  3. Modular Code:

    • Break Down Large Problems: Split large tasks into smaller, manageable functions. This helps with code organization and makes debugging easier.

    • Single Responsibility Principle: Each function should perform one specific task. Avoid writing functions that do too many things.

      • Example:

        // Function 1: Calculate total price
        function calculateTotalPrice(price, tax) {
          return price + tax;
        }
        
        // Function 2: Apply discount
        function applyDiscount(price, discount) {
          return price - discount;
        }
        
        // Function 3: Calculate final price
        function calculateFinalPrice(price, tax, discount) {
          let total = calculateTotalPrice(price, tax);
          return applyDiscount(total, discount);
        }
  4. Avoid Side Effects:

    • Functions should avoid modifying global variables or data outside of their scope unless necessary. This helps to avoid unexpected behavior and makes the function more predictable and easier to test.

    • Example:

      // Avoid modifying global variables
      let globalCount = 0;
      function incrementCount() {
        globalCount++;  // Modifying global variable directly can lead to side effects
      }

Student Activity (10 mins):

Objective: Students will practice writing functions using best practices such as clear naming, reusability, and modularity.


Step-by-Step Activity:

  1. Create an HTML file (e.g., functions_best_practices.html) and write JavaScript code following the best practices for function naming, reusability, and modularity.

  2. Example Code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Best Practices for Functions</title>
    </head>
    <body>
      <h1>Check the Console for Function Outputs</h1>
    
      <script>
        // 1. Clear and descriptive function names
        function calculateArea(length, width) {
          return length * width;
        }
        let area = calculateArea(10, 5);
        console.log("Area of the rectangle is: " + area);  // Outputs: Area of the rectangle is: 50
    
        // 2. Reusable function
        function getDiscountedPrice(price, discount) {
          return price - discount;
        }
        console.log("Price after discount: " + getDiscountedPrice(100, 20));  // Outputs: 80
        console.log("Price after discount: " + getDiscountedPrice(50, 5));    // Outputs: 45
    
        // 3. Modular code (function breakdown)
        function getPriceWithTax(price, tax) {
          return price + (price * tax);
        }
        function applyDiscount(price, discount) {
          return price - discount;
        }
        function calculateFinalAmount(price, tax, discount) {
          let priceWithTax = getPriceWithTax(price, tax);
          return applyDiscount(priceWithTax, discount);
        }
        let finalAmount = calculateFinalAmount(100, 0.1, 10);  // price: 100, tax: 10%, discount: 10
        console.log("Final amount to be paid: " + finalAmount);  // Outputs: 100
      </script>
    </body>
    </html>
  3. Run the file in a browser:

    • Open the HTML file in a browser and use Developer Tools (F12 or right-click and select Inspect > Console) to view the outputs.

  4. Activity:

    • Step 1: Write a reusable function that calculates the perimeter of a rectangle and print the result.

      function calculatePerimeter(length, width) {
        return 2 * (length + width);
      }
      console.log("Perimeter of the rectangle is: " + calculatePerimeter(10, 5));  // Outputs: Perimeter of the rectangle is: 30
    • Step 2: Modify the code by breaking down complex tasks into smaller functions:

      • Break down a task like calculating the total cost of a meal (including tax and tip) into separate functions for calculating tax, tip, and final cost.

      function calculateTax(amount, taxRate) {
        return amount * taxRate;
      }
      
      function calculateTip(amount, tipRate) {
        return amount * tipRate;
      }
      
      function calculateTotalMealCost(amount, taxRate, tipRate) {
        let tax = calculateTax(amount, taxRate);
        let tip = calculateTip(amount, tipRate);
        return amount + tax + tip;
      }
      
      let totalCost = calculateTotalMealCost(50, 0.1, 0.15);
      console.log("Total meal cost: " + totalCost);  // Outputs: Total meal cost: 62.5

Activity Follow-up Questions:

  1. Why is it important to use clear and descriptive names for functions?

  2. How can writing reusable functions make your code more efficient and easier to maintain?

  3. What is the benefit of breaking down a large task into smaller functions (modularity)?


Expected Outcome:

Students will:

  • Understand how to write functions with clear, descriptive names that follow common naming conventions.

  • Practice writing reusable functions that avoid hardcoding and can be used in multiple places.

  • Learn how to break down complex tasks into smaller functions to create more modular and maintainable code.

Challenge Activity

Goal: create a login page with First Name, Last Name, and Email Address fields, along with email validation

Procedure

a step-by-step guide and code for creating a login page with First Name, Last Name, and Email Address fields, along with email validation using JavaScript.

  1. HTML Structure:

    • A simple form with three fields:

      • First Name and Last Name use <input type="text">.

      • Email Address uses <input type="email"> for basic HTML validation.

    • A button for submitting the form.

  2. Styling:

    • Basic CSS styles are applied to give the form a neat and user-friendly appearance.

    • Error messages are displayed in red using the .error class.

  3. JavaScript Validation:

    • The email validation is handled using a regular expression (emailRegex) that matches standard email formats.

    • When the form is submitted:

      • The submit event listener checks if the email is valid using the validateEmail() function.

      • If invalid, the form submission is prevented, and an error message is displayed in the emailError <div>.

  4. Email Validation Regex:

    • The regex /^[^\s@]+@[^\s@]+\.[^\s@]+$/ checks:

      • No whitespace before the @ symbol.

      • A valid domain structure (e.g., example.com).

  5. Success Message:

    • If all fields are valid, an alert message is displayed for demonstration purposes.


How It Works:

  1. Open the HTML file in a browser.

  2. Fill out the form:

    • If the email is invalid, an error message will appear below the email field.

    • If all fields are valid, a success message will be shown.

  3. The form ensures that users provide valid input before proceeding.

This form can be extended with more validation or connected to a backend server for processing user data.

Last updated