Skip to main content

Closures


Closures is (a fancy term for) a function that remembers outside things that are used inside

const createPrinter() {
  const name = 'Alex'

  const printName = () => {
    console.log(name)
  }
  return printName
}

const myPrinter = createPrinter()

myPrinter() // Alex


This function that was return from from createPrinter function is called a closure. // Here is printName
Closure is a combination of a function and the environment where it was declared.

Comments

Popular posts from this blog

Array.fill()

Caveat: If you .fill() an Array with an object, all elements refer to the same instance (i.e., the object isn’t cloned) So if you do something like: let a = Array(3).fill([]) // create an array named a and fill it with 3 empty array a[2].push('poop') // push new value to the element array at index 2 expect [ [], [], [2]] But because all element refer to the same instance, so the result is: [[2], [2], [2]] More details here:  https://2ality.com/2018/12/creating-arrays.html