← JavaScript

Functions

What is the difference between a regular function and an arrow function?

Show answer — try answering out loud first

Arrow functions don't have their own this (they inherit it from the scope where they're defined), don't have arguments, can't be used as constructors, and have shorter syntax. Regular functions do have their own this and arguments.

The main differences:

  • this: the most important one. A regular function defines its own this based on how it's called. An arrow function has no this of its own: it uses the one from the scope where it was created. That's why arrows are ideal for callbacks inside methods.
  • arguments: regular functions have the arguments object; arrows don't.
  • Constructor: you can do new Funcion() with a regular one, but not with an arrow.
  • Syntax: arrows are shorter, and with a single return they can omit the braces and the return.
// Syntax
const sumar = (a, b) => a + b;       // implicit return
const cuadrado = n => n * n;         // single parameter, no parentheses
function sumarNormal(a, b) { return a + b; }

// The big difference: this
const objeto = {
  nombre: "Mike",
  saludarNormal: function () {
    setTimeout(function () {
      // here, this is NOT the object (it's undefined or the global)
      console.log("Normal:", this.nombre); // undefined
    }, 0);
  },
  saludarArrow: function () {
    setTimeout(() => {
      // the arrow inherits the this from saludarArrow, which is the object
      console.log("Arrow:", this.nombre); // "Mike"
    }, 0);
  },
};

objeto.saludarNormal(); // Normal: undefined
objeto.saludarArrow();  // Arrow: Mike

Using an arrow function as an object method expecting this to be the object:

const obj = {
  nombre: "Mike",
  saludar: () => console.log(this.nombre), // this is NOT obj
};
obj.saludar(); // undefined

For object methods, use regular functions; for internal callbacks, use arrow functions.

"The most important difference is this. A regular function has its own this based on how it's called, while an arrow function inherits this from the scope where it's defined. In addition, arrows don't have arguments, can't be used with new, and have shorter syntax. That's why I use arrow functions for callbacks, especially inside methods, and regular functions when I need my own this or a constructor."

Quick challenge

What does this print?

const persona = {
  edad: 30,
  crecer: () => {
    this.edad++;
    return this.edad;
  },
};
console.log(persona.crecer());
See answer

It prints NaN. Since crecer is an arrow function, its this is not persona, so this.edad is undefined, and undefined++ gives NaN.