Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Function Closures in JavaScript

Function Closures in JavaScript

? Function Closures in JavaScript


What is a Closure?

  • A closure is a function that remembers and accesses variables from its lexical scope even when that outer function has finished executing.

  • It “closes over” variables from its surrounding context.


Why are Closures Useful?

  • To encapsulate private variables.

  • To maintain state between function calls.

  • To create factory functions and callbacks with preserved data.


How Closures Work: Basic Example

function outer() {  let count = 0;  // variable in outer scope  function inner() {    count++;             // accesses and updates outer variable    console.log(count);  }  return inner;}const counter = outer();counter(); // Output: 1counter(); // Output: 2counter(); // Output: 3
  • inner() forms a closure that keeps the count variable alive even after outer() returns.


Another Example: Private Variables

function makeCounter() {  let count = 0;  return {    increment: function() {      count++;      return count;    },    decrement: function() {      count--;      return count;    }  };}const counter = makeCounter();console.log(counter.increment()); // 1console.log(counter.increment()); // 2console.log(counter.decrement()); // 1
  • The variable count is private and can only be accessed/modified via the returned methods.


Important Notes

  • Closures capture variables, not their values. So if the variable changes, closures see the updated value.

  • Beware of common pitfalls with closures in loops (use let instead of var).


Summary

AspectDescription
ClosureFunction + preserved outer scope
Useful forData privacy, stateful functions
Keeps variables aliveEven after outer function ends

Want me to explain common closure pitfalls or how closures power module patterns?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql