By Felix Kling


2015-12-18 17:58:00 8 Comments

Arrow functions in ES2015 provide a more concise syntax.

  • Can I replace all my function declarations / expressions with arrow functions now?
  • What do I have to look out for?

Examples:

Constructor function

function User(name) {
  this.name = name;
}

// vs

const User = name => {
  this.name = name;
};

Prototype methods

User.prototype.getName = function() {
  return this.name;
};

// vs

User.prototype.getName = () => this.name;

Object (literal) methods

const obj = {
  getName: function() {
    // ...
  }
};

// vs

const obj = {
  getName: () => {
    // ...
  }
};

Callbacks

setTimeout(function() {
  // ...
}, 500);

// vs

setTimeout(() => {
  // ...
}, 500);

Variadic functions

function sum() {
  let args = [].slice.call(arguments);
  // ...
}

// vs
const sum = (...args) => {
  // ...
};

3 comments

@S. Mayol 2019-02-18 23:44:39

JavaScript Arrow Functions are just another way of defining function.

Arrow Functions not only makes your code looks more clean, concrete, and easier to read. It also provides the benefits of the implicit return.

Below I am sharing some simple examples that self explain the declaration of a function and how to define JavaScript Arrow Functions.

/*----------------------------------
    JavaScript Arrow Functions 
  ----------------------------------*/

// Defining a function.
function addNumbers(a, b) {
    return a + b;
}

addNumbers(10, 6);  // 16

// Using anonymous function.
var addNumbers = function(a, b) {
    return a + b;
}

addNumbers(10, 6); // 16

// using Arrow Functions or Fat Arrow functions.
var addNumbers = (a, b) => {
    return a + b; // with return statement
}

addNumbers(10, 6); // 16

// Using Arrow Functions or Fat Arrow functions without return statements and without curly braces.
var addNumbers = (a, b) => a + b; // this is a condensed way to define a function.

addNumbers(10, 6); // 16

Here I will provide you a link about JavaScript Arrow Functions: How, Why, When (and WHEN NOT) to Use Them where is going to guide you with examples and details...

@nikk wong 2019-04-02 04:34:19

This ignores the fact that arrow functions have different lexical scoping than traditional functions.

@S. Mayol 2019-04-25 00:54:33

Hi Nikk, this is just a basic explanation about how you can turn a regular Function into an Arrow Function. Ath the end i posted a link about an article that explains more in details about JavaScript Arrow Functions: How, Why, When (and WHEN NOT) to Use Them.

@Quentin 2019-05-28 11:40:58

The first line of this answer is highly misleading. The massively significant differences aren't even mentioned in the question but are left for another site to explain with a link at the very end of the answer.

@Felix Kling 2015-12-18 17:58:00

tl;dr: No! Arrow functions and function declarations / expressions are not equivalent and cannot be replaced blindly.
If the function you want to replace does not use this, arguments and is not called with new, then yes.


As so often: it depends. Arrow functions have different behavior than function declarations / expressions, so lets have a look at the differences first:

1. Lexical this and arguments

Arrow functions don't have their own this or arguments binding. Instead, those identifiers are resolved in the lexical scope like any other variable. That means that inside an arrow function, this and arguments refer to the values of this and arguments in the environment the arrow function is defined in (i.e. "outside" the arrow function):

// Example using a function expression
function createObject() {
  console.log('Inside `createObject`:', this.foo);
  return {
    foo: 42,
    bar: function() {
      console.log('Inside `bar`:', this.foo);
    },
  };
}

createObject.call({foo: 21}).bar(); // override `this` inside createObject

// Example using a arrow function
function createObject() {
  console.log('Inside `createObject`:', this.foo);
  return {
    foo: 42,
    bar: () => console.log('Inside `bar`:', this.foo),
  };
}

createObject.call({foo: 21}).bar(); // override `this` inside createObject

In the function expression case, this refers to the object that was created inside the createObject. In the arrow function case, this refers to this of createObject itself.

This makes arrow functions useful if you need to access the this of the current environment:

// currently common pattern
var that = this;
getData(function(data) {
  that.data = data;
});

// better alternative with arrow functions
getData(data => {
  this.data = data;
});

Note that this also means that is not possible to set an arrow function's this with .bind or .call.

If you are not very familiar with this, consider reading

2. Arrow functions cannot be called with new

ES2015 distinguishes between functions that are callable and functions that are constructable. If a function is constructable, it can be called with new, i.e. new User(). If a function is callable, it can be called without new (i.e. normal function call).

Functions created through function declarations / expressions are both constructable and callable.
Arrow functions (and methods) are only callable. class constructors are only constructable.

If you are trying to call a non-callable function or to construct a non-constructable function, you will get a runtime error.


Knowing this, we can state the following.

Replaceable:

  • Functions that don't use this or arguments.
  • Functions that are used with .bind(this)

Not replaceable:

  • Constructor functions
  • Function / methods added to a prototype (because they usually use this)
  • Variadic functions (if they use arguments (see below))

Lets have a closer look at this using your examples:

Constructor function

This won't work because arrow functions cannot be called with new. Keep using a function declaration / expression or use class.

Prototype methods

Most likely not, because prototype methods usually use this to access the instance. If they don't use this, then you can replace it. However, if you primarily care for concise syntax, use class with its concise method syntax:

class User {
  constructor(name) {
    this.name = name;
  }

  getName() {
    return this.name;
  }
}

Object methods

Similarly for methods in an object literal. If the method wants to reference the object itself via this, keep using function expressions, or use the new method syntax:

const obj = {
  getName() {
    // ...
  },
};

Callbacks

It depends. You should definitely replace it if you you are aliasing the outer this or are using .bind(this):

// old
setTimeout(function() {
  // ...
}.bind(this), 500);

// new
setTimeout(() => {
  // ...
}, 500);

But: If the code which calls the callback explicitly sets this to a specific value, as is often the case with event handlers, especially with jQuery, and the callback uses this (or arguments), you cannot use an arrow function!

Variadic functions

Since arrow functions don't have their own arguments, you cannot simply replace them with an arrow function. However, ES2015 introduces an alternative to using arguments: the rest parameter.

// old
function sum() {
  let args = [].slice.call(arguments);
  // ...
}

// new
const sum = (...args) => {
  // ...
};

Related question:

Further resources:

@loganfsmyth 2015-12-18 22:13:55

Possibly worth mentioning that the lexical this also affects super and that they have no .prototype.

@JMM 2016-04-01 22:49:48

It would also be good to mention that they aren't syntactically interchangeable -- an arrow function (AssignmentExpression) can't just be dropped in everywhere a function expression (PrimaryExpression) can and it trips people up fairly frequently (especially since there've been parsing errors in major JS implementations).

@Felix Kling 2016-04-01 22:54:46

@JMM: "it trips people up fairly frequently" can you provide a concrete example? Skimming over the spec, it seems that the places where you can put a FE but not an AF would result in runtime errors anyway...

@JMM 2016-04-01 23:27:29

Sure, I mean stuff like trying to immediately invoke an arrow function like a function expression (() => {}()) or do something like x || () => {}. That's what I mean: runtime (parse) errors. (And even though that's the case, fairly frequently people think the error is in error.) Are you just trying to cover logic errors that would go unnoticed because they don't necessarily error when parsed or executed? new'ing one is a runtime error right?

@JMM 2016-04-01 23:27:34

Here are some links of it coming up in the wild: substack/node-browserify#1499, babel/babel-eslint#245 (this is an async arrow, but I think it's the same basic issue), and a bunch of issues on Babel that are hard to find now, but here's one T2847.

@Felix Kling 2016-04-01 23:31:19

@JMM: I see what you mean. Yeah, I was more focused on behavior, less on syntax. But I can expand on that in the answer. Or feel free to edit it yourself :) "new'ing one is a runtime error right?" Yes.

@JMM 2016-04-01 23:42:25

Ok cool. I think it'd be helpful to explain because I think people already find it surprising and would find it more so after reading a breakdown of how they're not interchangeable that didn't mention it. But it's true that in a non-bugged implementation it won't fly under the radar (though like I mentioned people tend to find it so surprising / are so used to a bugged implementation that they think the error is a bug.)

@Evan Carroll 2016-06-03 23:25:42

I'm not a fan of this answer because storing that outside the function and writing it with this is not always guaranteed to work in the case of nested objects/functions. It depends on where that is set to this. I see what you're trying to demonstrate, but there is a huge chance of misreading it. Anon functions provide some capabilities that can not be recreated with the short hand and that point should be the one you're driving home.

@Felix Kling 2016-06-04 01:51:21

@EvanCarroll: I don't mean to promote the var that = this; pattern. This is just included because it is a common pattern and exactly the one that arrow functions are supposed to replace.

@candy_man 2017-12-06 07:39:21

@FelixKling Great grasp of important concepts. Though I just noticed you missed the difference between function expressions and function declarations. Function declarations statements will always begin with the function keyword while function expressions begin with anything other than the function keyword. This is what makes IIFEs, a function assigned to a variable among others function expressions as opposed to function declarations. Really good job though explaining all these. Kudos.

@Felix Kling 2017-12-09 13:57:55

@Paul: thank you! There are other q&a’s with more details on function declaration vs expression. This q&a assumes that the difference is known. While I understand what you are saying, it’s not quite correct: function expressions also always start with the function keyword, but what comes before the function keyword determines whether the function definition is interpreted as declaration or expression. That part is not part of the function expression though. E.g. if you have foo = function (){}, then the = is part of the assignment expression, not the function expression.

@Felix Kling 2017-12-09 13:59:15

@PaulUpendo: Have a look at astexplorer.net if you are interested in how JavaScript programs are constructed syntactically (or at least what the AST looks like that popular JS parsers produce).

@candy_man 2017-12-11 06:54:37

@FelixKling Function Declaration Image on astexplorer.net : ibb.co/dKjY9b vs Function Expression Image on astexplorer.net : ibb.co/itp0pb

@Felix Kling 2017-12-11 17:22:51

@PaulUpendo: Right. And if you hover over the function expression in the tree view you can see that the (...)() part is not part of the function expression. That’s all that I’m saying.

@Dan Dascalescu 2018-08-13 22:17:09

At the file level, there is no difference between function foo(...) { return ... } and const foo = (...) => { return ... }, yet I see the latter pattern used very frequently, especially in React libraries. Why create an anonymous function and assign it to a constant, when a regular function declaration would do the same thing?

@Felix Kling 2018-08-13 22:26:19

@Dan: ¯\_(ツ)_/¯ ... people like to use new things maybe? In theory you can overwrite foo in the first case later, while const prevents that. Not sure that's the reason though.

@Ini 2018-09-04 16:07:40

In your first example you do not overwrite anything... you just return a other object then you pass to the this-parameter of call()

@abbaf33f 2016-09-12 14:01:19

Look at this Plnkr example

The variable this is very different timesCalled increments only by 1 each time the button is called. Which answers my personal question:

.click( () => { } )

and

.click(function() { })

both create the same number of functions when used in a loop as you can see from the Guid count in the Plnkr.

Related Questions

Sponsored Content

23 Answered Questions

[SOLVED] Set a default parameter value for a JavaScript function

45 Answered Questions

[SOLVED] JavaScript equivalent to printf/String.Format

9 Answered Questions

7 Answered Questions

[SOLVED] What do multiple arrow functions mean in javascript?

13 Answered Questions

[SOLVED] jQuery document.createElement equivalent?

40 Answered Questions

[SOLVED] Is there an "exists" function for jQuery?

  • 2008-08-27 19:49:41
  • Jake McGraw
  • 711301 View
  • 2568 Score
  • 40 Answer
  • Tags:   javascript jquery

37 Answered Questions

[SOLVED] var functionName = function() {} vs function functionName() {}

33 Answered Questions

[SOLVED] $(document).ready equivalent without jQuery

  • 2009-04-28 21:51:11
  • FlySwat
  • 932939 View
  • 1827 Score
  • 33 Answer
  • Tags:   javascript jquery

1 Answered Questions

3 Answered Questions

[SOLVED] ECMAScript 6 arrow function that returns an object

Sponsored Content