Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Arrow Functions vs Traditional Functions in JavaScript

1 min read .
Arrow Functions vs Traditional Functions in JavaScript

JavaScript gives you several ways to define functions. Arrow functions are compact and capture lexical this, while traditional functions have their own this behavior and can be used as constructors.

1. Common Function Forms

Function declaration:

function greet(name) {
  return `Hello, ${name}!`;
}

Function expression:

const greet = function (name) {
  return `Hello, ${name}!`;
};

Arrow function:

const greet = (name) => `Hello, ${name}!`;

2. Important Differences

Syntax

Arrow functions are often convenient for short callbacks and small transformations:

const doubled = [1, 2, 3].map((value) => value * 2);

this

A traditional function gets this from how it is called. An arrow function does not create its own this; it closes over this from the surrounding lexical scope.

function Timer() {
  this.value = 42;

  setTimeout(function () {
    console.log(this.value);
  }, 100);

  setTimeout(() => {
    console.log(this.value);
  }, 100);
}

new Timer();

The arrow callback sees the Timer instance. The ordinary callback does not automatically inherit that instance as this.

arguments

Traditional non-arrow functions have an arguments object. Arrow functions do not create one.

Prefer rest parameters in new code when you need an explicit list of arguments:

function traditional(...args) {
  console.log(args);
}

const arrow = (...args) => {
  console.log(args);
};

Constructors

Arrow functions cannot be called with new and do not have a prototype property for constructor use.

const Person = (name) => ({ name });
// new Person('Alice') -> TypeError

Use a class or traditional function when constructor behavior is required.

3. Which Should You Use?

Prefer an arrow function when Prefer a traditional function when
you want lexical this the call site should determine this
writing a concise callback defining a constructor function
a short expression reads clearly function declarations improve structure or hoisting is useful
you do not need an own arguments object you intentionally rely on traditional function semantics

4. Practical Advice

Do not choose arrow functions only because they are shorter. The important difference is semantics, especially around this, arguments, constructors, and methods.

Object methods that use this are usually clearer with method syntax:

const user = {
  name: 'Alice',
  greet() {
    return `Hello, ${this.name}`;
  },
};

Conclusion

Arrow functions and traditional functions are both useful. Arrow functions are excellent for callbacks and lexical this; traditional functions remain the right tool for constructors and contexts where invocation-defined this matters. Choose based on behavior first and syntax second.

Related Posts

chevron-up