Skip to content

Instantly share code, notes, and snippets.

@smarteist
Created April 24, 2026 18:52
Show Gist options
  • Select an option

  • Save smarteist/08730b3a23e3c022cbeddedec686f567 to your computer and use it in GitHub Desktop.

Select an option

Save smarteist/08730b3a23e3c022cbeddedec686f567 to your computer and use it in GitHub Desktop.

Arrow functions — simple comparison

ES5 (need .bind to keep this):

const result = {
  name: "Hello",
  data: function () {
    setTimeout(function () {
      console.log(this.name);
    }.bind(this), 5000);
  }
};

ES6 (arrow keeps surrounding this):

const result = {
  name: "Hello",
  data() {
    setTimeout(() => {
      console.log(this.name);
    }, 5000);
  }
};

Key takeaway: arrow functions inherit this from the outer scope; regular functions get their own this.


Closures — quick pattern

Factory that returns a function which "remembers" i:

function getAdder(i) {
  return function (number) {
    return i + number;
  };
}

const add6 = getAdder(6);
console.log(add6(4));        // 10
console.log(getAdder(6)(4)); // 10

Takeaway: inner function retains access to outer scope variables even after outer returns.


Stale closures and incrementer example — step-by-step

Small demo: simple curried function

const closure = a => b => console.log(a, b);
closure(1)(2); // 1 2

Incrementer that returns helpers and shows how closures capture current values:

function createIncrement(init = 0) {
  let value = init;

  return function increment() {
    value += 1;
    console.log(value); // current value

    const message = `Current value is ${value}`;

    function logger() {
      console.log(message); // message captured at this call
    }

    function getValue() {
      return value; // always reads latest value
    }

    return [logger, getValue];
  };
}

const counter = createIncrement(); // value starts 0

const [logger, getValue] = counter(); // value -> 1, message = 'Current value is 1'
counter(); // value -> 2
counter(); // value -> 3

logger();            // logs: 'Current value is 1'  (captured message)
console.log(getValue()); // logs: 3  (reads latest value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment