14.1 Introduction to Functions (15 mins)

  1. What Are Functions in Web Programming?

    • Definition: A function is a reusable block of code that performs a specific task. Functions help to organize and structure code by breaking it down into smaller, manageable pieces.

    • Why Are Functions Useful?:

      • Code Reusability: Instead of writing the same code multiple times, you can define a function and call it whenever needed.

      • Code Organization: Functions help keep code organized by grouping related operations together.

      • Modularity: Breaking a complex problem into smaller tasks makes the code easier to understand and debug.

      • Maintainability: If you need to update a certain behavior, you only have to modify the function definition in one place.

    Real-World Example:

    • Consider a web page where you need to validate user input in multiple forms (login, registration, and profile update). Instead of writing the same validation logic repeatedly, you can create a validateInput() function and reuse it across different forms.

  2. Syntax for Defining and Calling a Function:

    • Defining a Function:

      • Functions are defined using the function keyword, followed by the function name, parentheses (), and a code block {} containing the statements that make up the function.

      • Syntax:

        function functionName(parameters) {
          // Code to be executed
        }
      • Example: Define a function to calculate the square of a number:

        function square(num) {
          return num * num;  // Returns the square of the number
        }
    • Calling a Function:

      • Once a function is defined, you can call it by using the function name followed by parentheses. If the function expects parameters, pass the values inside the parentheses.

      • Syntax:

        functionName(arguments);
      • Example: Call the square() function:

        let result = square(4);  // Calls the function with 4 as an argument
        console.log(result);  // Outputs: 16
  3. Parameters and Arguments:

    • Parameters: These are placeholders defined in the function declaration that the function can use to perform operations.

    • Arguments: When calling a function, you pass values (arguments) to the parameters.

    • Example:

      function greet(name) {
        console.log("Hello, " + name);
      }
      greet("Alice");  // Outputs: Hello, Alice
  4. Return Values:

    • Functions can return a result using the return keyword. Once a value is returned, the function execution stops.

    • Example:

      function add(a, b) {
        return a + b;
      }
      let sum = add(5, 3);  // sum is 8
      console.log(sum);  // Outputs: 8

Student Activity (15 mins):

Objective: Students will practice defining and calling functions in JavaScript, using parameters and return values to perform calculations or print messages.


Step-by-Step Activity:

  1. Create an HTML file (e.g., functions_intro.html) and write JavaScript code that demonstrates the use of functions.

  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>Introduction to Functions</title>
    </head>
    <body>
      <h1>Check the Console for Function Outputs</h1>
    
      <script>
        // Function to greet a user
        function greet(name) {
          console.log("Hello, " + name);
        }
    
        // Function to add two numbers
        function add(a, b) {
          return a + b;
        }
    
        // Calling the functions
        greet("Alice");  // Outputs: Hello, Alice
        let result = add(5, 10);
        console.log("The sum of 5 and 10 is " + result);  // Outputs: The sum of 5 and 10 is 15
      </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 of the functions.

  4. Activity:

    • Step 1: Run the code and observe how the greet() and add() functions work.

    • Step 2: Modify the functions:

      • Create a new function called subtract() that subtracts two numbers and returns the result.

      • Create another function called multiply() that multiplies two numbers and prints the result.

    Challenge:

    • Write a function called isEven() that takes a number as an argument and returns true if the number is even and false if it’s odd.

      function isEven(num) {
        return num % 2 === 0;
      }
      
      console.log(isEven(4));  // Outputs: true
      console.log(isEven(7));  // Outputs: false

Activity Follow-up Questions:

  1. Why are functions important in web programming?

  2. What is the difference between parameters and arguments in a function?

  3. How does the return keyword work, and why is it useful?


Expected Outcome:

Students will:

  • Understand how to define and call functions in JavaScript.

  • Practice passing parameters to functions and using return values.

  • See how functions can make their code more organized and reusable in various scenarios.

Last updated