[{"data":1,"prerenderedAt":105},["ShallowReactive",2],{"course-en-closures":3},{"lesson":4,"number":96,"prev":97,"next":101},{"slug":5,"title":6,"description":9,"goal":11,"blocks":13,"summary":66,"exercises":77},"closures",{"ru":7,"en":8},"","Closures",{"ru":7,"en":10},"Closures in JavaScript: how a function remembers variables from where it was created, function factories, private state, the var loop trap and memory leaks.",{"ru":7,"en":12},"Understand how a function remembers the variables of the place where it was created, and learn to use closures for function factories and private state without falling into the var-in-a-loop trap.",[14,17,20,22,26,28,30,32,35,37,39,42,44,46,48,51,53,55,58,60,62,64],{"type":15,"ru":7,"en":16},"text","A closure is a function together with the variables of the place where it was created. In the \"First-class and higher-order functions\" lesson, functions returned other functions. The returned function keeps using the variables of the outer function even after that function has finished: it \"remembers\" them. In JavaScript every function gets a closure at the moment it is created; there is no special syntax for it.",{"type":18,"ru":7,"en":19},"heading","The lexical environment",{"type":15,"ru":7,"en":21},"Every function call, as well as every block with let and const declarations, creates a lexical environment: a record of local variables plus a reference to the outer environment. When a function is created, it stores a reference to the environment in which it was written; the specification calls this internal slot [[Environment]]. When the function needs a variable, the engine looks for it in the function's own environment, then in the outer one, and so on up to the global one. \"Lexical\" means that the chain is determined by where the function appears in the program text, not by where it is called.",{"type":23,"code":24},"code",{"ru":7,"en":25},"\u002F\u002F Scope is determined by the place where the function is written\n\u002F\u002F ===============================\nconst place = 'outside'\n\n\u002F\u002F readPlace :: () -> String\n\u002F\u002F readPlace is written at the top level and sees the top-level place\nconst readPlace = () => place\n\nconst callFromInside = () => {\n  const place = 'inside'\n  \u002F\u002F we call it from inside, but readPlace looks up place where it was written\n  return readPlace()\n}\n\nconsole.log(callFromInside()) \u002F\u002F outside\n\n\u002F\u002F A function remembers variables after the outer function has finished\n\u002F\u002F ===============================\n\u002F\u002F makeGreeting :: String -> (() -> String)\nconst makeGreeting = (name) => {\n  const greeting = `Hello, ${name}`\n  \u002F\u002F makeGreeting will finish, but greeting stays available to the returned function\n  return () => greeting\n}\n\nconst greetAnna = makeGreeting('Anna')\nconsole.log(greetAnna()) \u002F\u002F Hello, Anna\n\n\u002F\u002F A closure keeps a reference to the variable, not a copy of its value\n\u002F\u002F ===============================\nlet count = 0\nconst readCount = () => count\n\ncount = 5\nconsole.log(readCount()) \u002F\u002F 5: the function sees the current value of count",{"type":15,"ru":7,"en":27},"Note the last example: a closure keeps not a snapshot of values but a reference to the variables themselves. If a variable changes after the function was created, the function sees the new value. Both useful techniques and the best-known closure trap are built on this; the trap is covered below.",{"type":18,"ru":7,"en":29},"Function factories",{"type":15,"ru":7,"en":31},"A function factory is a function that creates and returns new functions configured by its arguments. Every call of the factory creates a new environment, so the resulting functions are independent: each one has its own values of the variables.",{"type":23,"code":33},{"ru":7,"en":34},"\u002F\u002F A function factory\n\u002F\u002F ===============================\n\u002F\u002F makeMultiplier :: Number -> (Number -> Number)\nconst makeMultiplier = (factor) => (x) => x * factor\n\n\u002F\u002F every call of the factory creates a new environment with its own factor\nconst double = makeMultiplier(2)\nconst triple = makeMultiplier(3)\n\nconsole.log([1, 2, 3].map(double)) \u002F\u002F [2, 4, 6]\nconsole.log([1, 2, 3].map(triple)) \u002F\u002F [3, 6, 9]\n\n\u002F\u002F makePriceLabel :: String -> (Number -> String)\nconst makePriceLabel = (currency) => (amount) => `${amount} ${currency}`\n\nconst inRubles = makePriceLabel('RUB')\nconst inEuros = makePriceLabel('EUR')\n\nconsole.log(inRubles(1500)) \u002F\u002F 1500 RUB\nconsole.log(inEuros(15)) \u002F\u002F 15 EUR",{"type":18,"ru":7,"en":36},"Private state",{"type":15,"ru":7,"en":38},"The variables of the outer function cannot be reached from outside: they can be read or changed only through the functions it returned. This is how JavaScript gets private state without classes. Since ES2022 classes have hash-prefixed fields for this (#count), but closures are still everywhere: in modules, event handlers, React hooks and Vue composables.",{"type":23,"code":40},{"ru":7,"en":41},"\u002F\u002F A counter with private state\n\u002F\u002F ===============================\n\u002F\u002F createCounter :: Number -> Object\nconst createCounter = (start) => {\n  let count = start \u002F\u002F there is no way to reach count from outside\n\n  return {\n    increment: () => {\n      count += 1\n      return count\n    },\n    reset: () => {\n      count = start\n      return count\n    },\n    value: () => count,\n  }\n}\n\nconst first = createCounter(0)\nconst second = createCounter(100)\n\nfirst.increment()\nfirst.increment()\nsecond.increment()\n\nconsole.log(first.value()) \u002F\u002F 2\nconsole.log(second.value()) \u002F\u002F 101: each counter has its own environment\nconsole.log(first.count) \u002F\u002F undefined: count is not a property of the object but a variable in the closure\n\nfirst.reset()\nconsole.log(first.value()) \u002F\u002F 0",{"type":15,"ru":7,"en":43},"Functions like these are not pure: increment() with no arguments returns a new number every time. This is acceptable when the state is hidden inside a small module and changes only through its functions; the \"Pure functions\" lesson says more about this. But the more functions share one piece of mutable state, the harder it is to tell who changed it and when.",{"type":18,"ru":7,"en":45},"Closures in currying and partial application",{"type":15,"ru":7,"en":47},"Currying and partial application rest entirely on closures. A curried function takes its arguments in parts and, while some are missing, returns a new function that remembers the ones already received. Partial application fixes some of the arguments in advance, and they are kept in a closure until the final call. Both techniques are covered in detail in the \"Currying\" and \"Partial application\" lessons; here the point is to see where exactly the arguments are stored.",{"type":23,"code":49},{"ru":7,"en":50},"\u002F\u002F Currying: a is kept in the closure until b arrives\n\u002F\u002F ===============================\n\u002F\u002F add :: Number -> Number -> Number\nconst add = (a) => (b) => a + b\n\nconst add10 = add(10) \u002F\u002F add has finished, but a = 10 is remembered\nconsole.log(add10(5)) \u002F\u002F 15\n\n\u002F\u002F Partial application: fixed is kept in the closure\n\u002F\u002F ===============================\n\u002F\u002F fixArgs :: ((a, b, ...) -> x, a, ...) -> ((b, ...) -> x)\nconst fixArgs = (fn, ...fixed) => (...rest) => fn(...fixed, ...rest)\n\n\u002F\u002F greet :: (String, String) -> String\nconst greet = (greeting, name) => `${greeting}, ${name}!`\n\nconst sayHello = fixArgs(greet, 'Hello')\nconsole.log(sayHello('Anna')) \u002F\u002F Hello, Anna!\nconsole.log(sayHello('Oleg')) \u002F\u002F Hello, Oleg!",{"type":18,"ru":7,"en":52},"The trap: var in a loop",{"type":15,"ru":7,"en":54},"The classic closure mistake is callbacks created in a loop with var. The scope of a var is the whole function, so the entire loop has a single variable i. All three callbacks close over the same variable, and setTimeout calls them after the loop has finished and i equals 3. With let in the header of a for loop, every iteration gets a new variable holding the value from the previous step, so each callback gets its own.",{"type":23,"code":56},{"ru":7,"en":57},"\u002F\u002F var: a single variable i for the whole loop\n\u002F\u002F ===============================\nconst withVar = () => {\n  for (var i = 0; i \u003C 3; i++) {\n    setTimeout(() => console.log(`var: ${i}`), 0)\n  }\n}\n\n\u002F\u002F let: every iteration has its own variable i\n\u002F\u002F ===============================\nconst withLet = () => {\n  for (let i = 0; i \u003C 3; i++) {\n    setTimeout(() => console.log(`let: ${i}`), 0)\n  }\n}\n\nwithVar()\nwithLet()\n\u002F\u002F the callbacks run after both loops have finished:\n\u002F\u002F var: 3\n\u002F\u002F var: 3\n\u002F\u002F var: 3\n\u002F\u002F let: 0\n\u002F\u002F let: 1\n\u002F\u002F let: 2",{"type":15,"ru":7,"en":59},"Before let arrived in ES2015, the mistake was fixed with a function: the callback was created inside another function that received the current value of i, either an immediately invoked one (IIFE) or a factory. Every call of that function created a new environment, and the callback remembered its own value. You will try this approach in the exercise.",{"type":18,"ru":7,"en":61},"Closures and memory",{"type":15,"ru":7,"en":63},"As long as a function is reachable, its environment stays in memory too: the garbage collector cannot free variables the function might read. That alone is not a leak: once nothing references the function, its environment is freed as well. A leak starts when a function lives longer than needed and holds on to large data: an event handler nobody removed, a setInterval without clearInterval, an array of callbacks in a module that only grows.",{"type":15,"ru":7,"en":65},"To keep a closure from holding on to too much, remove handlers and timers once they are no longer needed, and do not capture large objects whole: take the values you need out of them before creating the function. Engines help, but not with everything. V8, for example, keeps only the variables that at least one inner function uses, but those variables are shared by all the functions created during one call of the outer function. If one of them reads a large array, the array stays in memory while any function from that call is alive, even one that never reads it.",[67,69,71,73,75],{"ru":7,"en":68},"A closure is a function together with the variables of the place where it was created. The function remembers them even after the outer function has finished.",{"ru":7,"en":70},"Scope is lexical: a variable is looked up where the function is written, not where it is called. A closure keeps a reference to the variable, not a copy of its value.",{"ru":7,"en":72},"Every call of the outer function creates a new environment, so function factories produce independent functions, and state in a closure cannot be reached from outside. Currying and partial application rest on the same mechanism.",{"ru":7,"en":74},"A var in a loop is one variable for all iterations, so setTimeout callbacks see the last value; let creates a new variable on every iteration.",{"ru":7,"en":76},"A closure keeps its environment in memory as long as the function is reachable: remove handlers and timers, and do not capture large objects whole.",[78,87],{"task":79,"starter":81,"solution":83,"expected":85},{"ru":7,"en":80},"Write a higher-order function once: it takes a function fn and returns a new function that calls fn only the first time and returns the remembered result on later calls. Keep the \"already called\" flag and the result in a closure.",{"ru":7,"en":82},"\u002F\u002F once :: (a -> b) -> (a -> b)\n\u002F\u002F your code\n\nlet calls = 0\n\n\u002F\u002F loadSettings :: String -> String\nconst loadSettings = (name) => {\n  calls += 1\n  return `settings for ${name}`\n}\n\nconst loadOnce = once(loadSettings)\n\nconsole.log(loadOnce('app'))\nconsole.log(loadOnce('admin')) \u002F\u002F loadSettings is not called, the first result is returned\nconsole.log(`loadSettings called: ${calls}`)",{"ru":7,"en":84},"\u002F\u002F once :: (a -> b) -> (a -> b)\n\u002F\u002F done and result live in the closure of the returned function\nconst once = (fn) => {\n  let done = false\n  let result\n\n  return (...args) => {\n    if (!done) {\n      done = true\n      result = fn(...args)\n    }\n    return result\n  }\n}\n\nlet calls = 0\n\n\u002F\u002F loadSettings :: String -> String\nconst loadSettings = (name) => {\n  calls += 1\n  return `settings for ${name}`\n}\n\nconst loadOnce = once(loadSettings)\n\nconsole.log(loadOnce('app'))\nconsole.log(loadOnce('admin')) \u002F\u002F loadSettings is not called, the first result is returned\nconsole.log(`loadSettings called: ${calls}`)",{"ru":7,"en":86},"settings for app\nsettings for app\nloadSettings called: 1",{"task":88,"starter":90,"solution":92,"expected":94},{"ru":7,"en":89},"The loop should print \"task 1\", \"task 2\" and \"task 3\", but it prints \"task 4\" three times. Without changing var to let, fix it: write a factory makeTask(n) that returns a callback for setTimeout, and pass makeTask(i) to setTimeout. The line after the loop shows what i equals before any callback has run.",{"ru":7,"en":91},"\u002F\u002F makeTask :: Number -> (() -> undefined)\n\u002F\u002F your code\n\n\u002F\u002F right now every callback sees the same i and prints \"task 4\"\nfor (var i = 1; i \u003C= 3; i++) {\n  setTimeout(() => console.log(`task ${i}`), 0)\n}\n\nconsole.log(`the loop has finished, i = ${i}`)",{"ru":7,"en":93},"\u002F\u002F makeTask :: Number -> (() -> undefined)\n\u002F\u002F every call of makeTask creates a new environment with its own n\nconst makeTask = (n) => () => console.log(`task ${n}`)\n\nfor (var i = 1; i \u003C= 3; i++) {\n  setTimeout(makeTask(i), 0)\n}\n\nconsole.log(`the loop has finished, i = ${i}`)",{"ru":7,"en":95},"the loop has finished, i = 4\ntask 1\ntask 2\ntask 3",4,{"slug":98,"title":99},"first-class-and-higher-order-functions",{"ru":7,"en":100},"First-class and higher-order functions",{"slug":102,"title":103},"pure-functions",{"ru":7,"en":104},"Pure functions",1792684724207]