Function vs arrow syntax

ECMAScript 2015 spec

Originally published on Notion.

This article is the one originally posted with a few markup changes, spelling and grammatical fixes.

In JavaScript, there are two ways of defining functions: one using the function keyword available since day 1, and one using the arrow syntax introduced in ES6.

function helloWorld(name) {
  console.log(`Hello, ${name}!`);
}
const helloWorld = name => {
  console.log(`Hello, ${name}!`);
}

Most of the time, you are likely to see them as anonymous functions passed as callbacks or actions.

setTimeout(function() {
  console.log("Hello 5 seconds later");
}, 5000);
setTimeout(() => {
  console.log("Hello 5 seconds later");
}, 5000);

But what is the difference between these two?

Simply put, function binds the value for this when the function is declared, whereas the arrow syntax doesn’t. The value for this in an arrow function is inherited from the enclosing lexical scope.

Example

Here’s an example.

let someObject = {
  value: "This is a dummy value",

  functionSyntax: function() {
    console.log(this);
  },

  arrowSyntax: () => console.log(this)
}

someObject.functionSyntax();  // this == someObject
someObject.arrowSyntax();     // this == global object
// someObject.functionSyntax();
{
  value: 'This is a dummy value',
  functionSyntax: [Function: functionSyntax],
  arrowSyntax: [Function: arrowSyntax]
}

// someObject.arrowSyntax();
{
  // node.js global object
  // or web browser's Window object
}