MakeW3web

JavaScript Function scope (global, local) and closures

In JavaScript, understanding function scope and closures is crucial for managing variables and their visibility throughout your code. This knowledge helps prevent unintended side effects and aids in writing more modular and maintainable code.

  1. Function scope (global and local):

In JavaScript, variables have either global or local (function) scope, depending on where they are declared.

  • Global scope: If a variable is declared outside any function, it has global scope and is accessible from any part of the code, including within functions.

Example:

const globalVar = "I'm global!";

function logVar() {
  console.log(globalVar);
}

logVar(); // Output: I'm global!
  • Local (function) scope: If a variable is declared inside a function, it has local scope and is accessible only within that function.

Example:

function logVar() {
  const localVar = "I'm local!";
  console.log(localVar);
}

logVar(); // Output: I'm local!
console.log(localVar); // ReferenceError: localVar is not defined

In this example, trying to access `localVar` outside the `logVar` function results in a ReferenceError, as `localVar` has local scope and is not accessible outside the function.

  1. Closures:

A closure is a feature in JavaScript where an inner function has access to its containing (outer) function's variables and parameters, even after the outer function has completed execution. Closures are a powerful concept that allows you to create functions with behavior that depends on data that is not passed as parameters.

Example:

function createGreeting(greeting) {
  return function (name) {
    console.log(`${greeting}, ${name}!`);
  };
}

const greetHello = createGreeting("Hello");
const greetBonjour = createGreeting("Bonjour");

greetHello("John"); // Output: Hello, John!
greetBonjour("Jean"); // Output: Bonjour, Jean!

In this example, the `createGreeting` function returns an inner function that takes a `name` parameter. When the inner function is called, it has access to the `greeting` parameter from the outer function, even after the `createGreeting` function has completed execution. This behavior is possible because of closures.

Understanding function scope and closures in JavaScript is essential for managing variable visibility and lifetimes, preventing unintended side effects, and creating more modular and maintainable code. By using these concepts effectively, you can write more robust and flexible applications that are easier to understand and debug.

Was this page helpful?