Skip to content

Instantly share code, notes, and snippets.

@vxhviet
Last active June 9, 2023 13:06
Show Gist options
  • Save vxhviet/914173120e27d65056afd6805026dbed to your computer and use it in GitHub Desktop.
Save vxhviet/914173120e27d65056afd6805026dbed to your computer and use it in GitHub Desktop.

[JavaScript] - Regular function vs arrow function

Arrow Function

this inside arrow function

const alex = {
  firstName: 'Alex',
  year: 1990,
  calcAge: function () {
    console.log(this); // 1. this here is the alex object
    console.log(2037 - this.year);
  },

  greet: () => {
    // 2. `this` here actually refers to the window obj and as window doesn't have `firstName` it will show as undefined
    console.log(`Hey ${this.firstName}`);
  },
};
alex.greet(); // 3. arrow function doesn't have this, so it will show as undefined

var firstName2 = 'Matilda'; // 4. var create this property on the global object
alex.greet(); // 5. so this here will incorrectly point to Matilda

this inside regular function call

const bob = {
  firstName: 'Bob',
  year: 1990,
  calcAge: function () {
    console.log(2037 - this.year);

    const isMillenial = function () {
      console.log(this.year >= 1981 && this.year <= 1996); // 7. `this` in here will become undefined
    };
    isMillenial(); // 6. JS rule: inside a regular function call, `this` must be undefined
  },
};

// 8.
// Uncaught TypeError: Cannot read properties of undefined (reading 'year')
// `this` inside isMillenial is undefined, thus this.year will throw exception
bob.calcAge();

Solution 1

const carl = {
  firstName: 'Carl',
  year: 1990,
  calcAge: function () {
    console.log(2037 - this.year);

    const self = this; // 9. copy `this` (carl obj) to a new property
    const isMillenial = function () {
      console.log(self.year >= 1981 && self.year <= 1996); // 10. self is now correctly points to carl
    };
    isMillenial();
  },
};

carl.calcAge();

Solution 2

const danny = {
  firstName: 'Danny',
  year: 1990,
  calcAge: function () {
    console.log(2037 - this.year);

    const isMillenial = () => {
      console.log(this); // 11. arrow function doesn't have `this` and thus points to the outer scope which is danny
      console.log(this.year >= 1981 && this.year <= 1996);
    };
    isMillenial();
  },
};

danny.calcAge();

argument keyword

Only available in regular function

const addExpr = function (a, b) {
  console.log(arguments);
  return a + b;
};
addExpr(2, 5);
addExpr(2, 5, 8, 12); // still possible to add more arguments

var addArr = (a, b) => {
  console.log(arguments);
  return a + b;
};
addArr(1, 2); // arguments is undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment