3 - Functions and Scope

Functions in JavaScript

What is a Function?

  • Function: A reusable block of code that performs a specific task.

  • Benefits: Reusability, modularity, easier testing, and maintenance.

  • Anatomy of a Function: Consists of a function name, parameters (optional), a function body, and a return value (optional).

    • Syntax:

      function functionName(parameters) {
          // function body
          return value;  // optional
      }

Declaring Functions

  • Function Declaration:

    • Example:

      function greet() {
          console.log("Hello, World!");
      }
      greet();  // Output: "Hello, World!"
    • Hoisting: Function declarations are hoisted, meaning they can be called before they are defined in the code.

      greet();  // Output: "Hello again!"
      function greet() {
          console.log("Hello again!");
      }
  • Function Expression: A function assigned to a variable.

    • Example:

      const sayHello = function() {
          console.log("Hello from Function Expression!");
      };
      sayHello();  // Output: "Hello from Function Expression!"
    • Hoisting: Function expressions are not hoisted, which means they cannot be called before they are defined.

      // sayHello();  // Error: Cannot access 'sayHello' before initialization
      const sayHello = function() {
          console.log("Hello!");
      };
  • Arrow Functions: A concise way to write functions (introduced in ES6).

    • Syntax Examples:

      const add = (a, b) => a + b;
      console.log(add(3, 4));  // Output: 7
      
      const greet = () => console.log("Hello, Arrow Function!");
      greet();  // Output: "Hello, Arrow Function!"
    • When to Use: Arrow functions are ideal for callbacks and one-liners, but they do not have their own this.

Parameters and Arguments

  • Parameters: Placeholders for values the function can receive.

  • Arguments: Actual values passed to the function.

    • Example:

  • Default Parameters: Providing default values to parameters.

    • Example:

  • Rest Parameters: Collect multiple arguments into a single array.

    • Example:

Return Values

  • Returning Values: Functions can return values using the return statement.

    • Example:

  • Return Without Value: If no return is specified, the function returns undefined.

    • Example:

Scope in JavaScript

Types of Scope

  • Global Scope: Variables declared outside of any function, accessible anywhere in the code.

    • Example:

  • Local Scope: Variables declared inside a function, accessible only within that function.

    • Example:

Block Scope

  • Block Scope: Variables declared with let or const inside {} are scoped to that block.

    • Example:

  • var Scope Exception: Variables declared with var are function-scoped, not block-scoped.

    • Example:

Lexical Scope and Closures

  • Lexical Scope: Refers to the ability for a function to access variables from the parent scope in which it was defined.

    • Example:

  • Closures: Functions that remember the environment in which they were created, even after the outer function has finished executing.

    • Example:

    • Use Cases for Closures: Closures are useful for data privacy and creating functions with preserved data.

      • Example: Creating a private counter that cannot be directly modified from outside its scope.

Arrow Functions vs Regular Functions

  • this Keyword: Arrow functions do not have their own this context, they inherit this from the enclosing scope.

    • Example:

  • Arrow Functions as Methods: Avoid using arrow functions as methods within objects since they do not bind this.

    • Example:

Immediately Invoked Function Expressions (IIFE)

  • IIFE: A function that runs as soon as it is defined.

    • Syntax:

    • Use Case: Useful for creating a private scope to avoid polluting the global namespace, often used in module patterns.

  • IIFE with Parameters: You can pass arguments into an IIFE.

    • Example:

Summary

  • Functions: Essential for reusable code. Learn to use function declarations, expressions, arrow functions, and understand their nuances like hoisting.

  • Scope: Understand the difference between global, local, block scope, and how lexical scope impacts functions. Closures are powerful for preserving state and ensuring data privacy.

  • this Keyword: Arrow functions inherit this, while regular functions have their own this context. Use caution when using this in different function types.

  • IIFE: A way to create immediate private scopes to keep code modular and avoid global pollution.


Next Chapter: Advanced JavaScript Concepts

Last updated