JavaScript  

Chapter 6: JavaScript Functions: Reusable Code Blocks

Functions are fundamental building blocks in JavaScript. They allow you to encapsulate a block of code that performs a specific task, making your code reusable, organized, and easier to manage.

6.1. What are Functions?

A function is a set of statements that performs a task or calculates a value. It can be defined once and executed many times.

Benefits

  • Reusability: Write code once, use it multiple times.
  • Organization: Break down complex problems into smaller, manageable pieces.
  • Readability: Improve code clarity by giving meaningful names to tasks.
  • Maintainability: Changes to a task only need to be made in one place.

6.2. Declaring and Calling Functions

There are several ways to declare functions. The most common is a function declaration.

  • Declaration Syntax

    function functionName(parameter1, parameter2, ...) {
        // Code to be executed
        return result; // Optional: returns a value
    }
  • Calling (Invoking) a Function: To run the code inside a function, you call it by its name followed by parentheses().

    function greet() {
        console.log("Hello there!");
    }
    
    greet(); // Calls the function, Output: Hello there!

6.3. Function Parameters and Arguments

  • Parameters: Named variables listed in the function definition. They act as placeholders for values that will be passed into the function.
  • Arguments: The actual values passed to the function when it is called.
    ​
    function add(num1, num2) { // num1, num2 are parameters
        return num1 + num2;
    }
    
    let result = add(5, 3); // 5, 3 are arguments
    console.log(result); // Output: 8

6.4. return Statement

The return statement is used to send a value back from the function to the caller. When return is executed, the function stops executing.

  • Example

    function multiply(a, b) {
        return a * b; // Returns the product
        console.log("This line will not be executed."); // Unreachable code
    }
    
    let product = multiply(4, 2);
    console.log(product); // Output: 8

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

6.5. Function Scope (Global vs. Local)

  • Global Scope: Variables declared outside any function are global. They can be accessed from anywhere in the code, including inside functions.
  • Local Scope (Function Scope): Variables declared inside a function are local to that function. They cannot be accessed from outside the function.
    ​let globalVar = "I am global"; // Global variable
    
    function showScope() {
        let localVar = "I am local"; // Local variable
        console.log(globalVar); // Accessible
        console.log(localVar);  // Accessible
    }
    
    showScope();
    console.log(globalVar); // Accessible
    // console.log(localVar); // ReferenceError: localVar is not defined

6.6. Function Expressions vs. Declarations

  • Function Declaration (Hoisted)

    // You can call this before its definition due to hoisting
    sayHello(); // Output: Hello!
    
    function sayHello() {
        console.log("Hello!");
    }
  • Function Expression (Not Hoisted): A function defined as part of an expression (e.g., assigned to a variable).

    // sayHi(); // TypeError: sayHi is not a function (not hoisted like declarations)
    
    const sayHi = function() { // Anonymous function assigned to a const variable
        console.log("Hi there!");
    };
    
    sayHi(); // Output: Hi there!

    Function expressions are often preferred for their clearer execution flow, and when functions are passed as arguments to other functions.

6.7. Arrow Functions (ES6)

Introduced in ES6, arrow functions provide a more concise syntax for writing function expressions. They also handle the this keyword differently (which we'll cover later).

  • Basic Syntax

    // Traditional function expression
    const addTraditional = function(a, b) {
        return a + b;
    };
    
    // Arrow function
    const addArrow = (a, b) => {
        return a + b;
    };
    
    // Concise arrow function for single expression return
    const addConcise = (a, b) => a + b;
    
    console.log(addConcise(2, 3)); // Output: 5
  • No Parameters

    const greet = () => console.log("Greetings!");
    greet(); // Output: Greetings!
  • Single Parameter (parentheses optional):

    const square = num => num * num;
    console.log(square(4)); // Output: 16

Functions are the backbone of modular and reusable JavaScript code. In the next chapter, we'll explore how to work with collections of data using Arrays and Objects.