Module 8: Functions

Objective: Learn how to create, use, and understand functions in JavaScript, including parameters, return values, and why they are essential for reusable and organized code.

1. What Are Functions?

A function is a block of code designed to perform a specific task. Functions let you reuse code instead of writing it repeatedly.

Real-Life Analogy:

Think of a function as a coffee machine. You press a button (input), and it makes coffee (output). You don’t need to know the details of how it works; you just use it when you need coffee.

2. Why Use Functions?

  • Reusability: Write code once and use it many times.
  • Modularity: Break your program into smaller, manageable parts.
  • Readability: Makes your code easier to understand and maintain.

3. Creating a Function

A function is defined using the function keyword.

Syntax:

function functionName() {
    // Code to execute
}

Example:

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

4. Calling a Function

To execute a function, you "call" it by using its name followed by parentheses.

Example:

sayHello(); // Outputs: Hello, world!

5. Parameters and Arguments

Functions can accept parameters, which are like placeholders for values you pass into the function when you call it.

Syntax:

function functionName(parameter1, parameter2) {
    // Code to execute
}

Example:

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

greet("Alice"); // Outputs: Hello, Alice!
greet("Bob");   // Outputs: Hello, Bob!

6. Return Values

A function can return a value using the return keyword. This allows the function to "send back" a result.

Example:

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

let result = add(5, 3); // result is 8
console.log(result);    // Outputs: 8

7. Function Expressions

Functions can also be defined as expressions and stored in variables.

Syntax:

let functionName = function(parameter) {
    // Code to execute
};

Example:

let square = function(number) {
    return number * number;
};

console.log(square(4)); // Outputs: 16

8. Arrow Functions (ES6)

Arrow functions provide a shorter syntax for writing functions.

Syntax:

let functionName = (parameter) => {
    // Code to execute
};

Example:

let multiply = (a, b) => a * b;

console.log(multiply(2, 3)); // Outputs: 6

9. Function Scope

Variables declared inside a function are only accessible within that function. This is called function scope.

Example:

function example() {
    let message = "Hello!";
    console.log(message); // Accessible inside the function
}

example();
// console.log(message); // Error: message is not defined

10. Practical Examples

Example 1: Calculating the Area of a Rectangle

function calculateArea(length, width) {
    return length * width;
}

console.log(calculateArea(5, 10)); // Outputs: 50

Example 2: Checking if a Number is Even or Odd

function isEven(number) {
    return number % 2 === 0;
}

console.log(isEven(4)); // Outputs: true
console.log(isEven(7)); // Outputs: false

11. Practice Exercises

Task 1: Greeting Function

Write a function that takes a name as a parameter and returns a personalized greeting.

Example Solution:

function greet(name) {
    return "Hello, " + name + "!";
}

console.log(greet("Alice")); // Outputs: Hello, Alice!

Task 2: Temperature Converter

Write a function that converts Celsius to Fahrenheit.

Example Solution:

function toFahrenheit(celsius) {
    return (celsius * 9) / 5 + 32;
}

console.log(toFahrenheit(0)); // Outputs: 32
console.log(toFahrenheit(25)); // Outputs: 77

Task 3: Sum of an Array

Write a function that takes an array of numbers and returns the sum of its elements.

Example Solution:

function sumArray(numbers) {
    let sum = 0;
    for (let num of numbers) {
        sum += num;
    }
    return sum;
}

console.log(sumArray([1, 2, 3, 4])); // Outputs: 10

12. Common Errors

  1. Forgetting to Call the Function:

    function sayHello() {
        console.log("Hello!");
    }
    
    // Nothing happens because the function is not called
  2. Not Returning a Value:

    function add(a, b) {
        a + b; // Missing return statement
    }
    
    console.log(add(2, 3)); // Outputs: undefined
  3. Using the Wrong Number of Arguments:

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

13. Challenge: BMI Calculator

Write a function to calculate Body Mass Index (BMI). The formula is:

BMI = weight (kg) / (height (m) * height (m))

Example Solution:

function calculateBMI(weight, height) {
    return weight / (height * height);
}

console.log(calculateBMI(70, 1.75)); // Outputs: 22.857142857142858