Categories
arrow-functions ecmascript-6 javascript syntax

What’s the meaning of “=>” (an arrow formed from equals & greater than) in JavaScript?

499

I know that the >= operator means more than or equal to, but I’ve seen => in some source code. What’s the meaning of that operator?

Here’s the code:

promiseTargetFile(fpParams, aSkipPrompt, relatedURI).then(aDialogAccepted => {
    if (!aDialogAccepted)
        return;

    saveAsType = fpParams.saveAsType;
    file = fpParams.file;

    continueSave();
}).then(null, Components.utils.reportError);

1

610

What It Is

This is an arrow function. Arrow functions are a short syntax, introduced by ECMAscript 6, that can be used similarly to the way you would use function expressions. In other words, you can often use them in place of expressions like function (foo) {...}. But they have some important differences. For example, they do not bind their own values of this (see below for discussion).

Arrow functions are part of the ECMAscript 6 specification. They are not yet supported in all browsers, but they are partially or fully supported in Node v. 4.0+ and in most modern browsers in use as of 2018. (I’ve included a partial list of supporting browsers below).

You can read more in the Mozilla documentation on arrow functions.

From the Mozilla documentation:

An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target). Arrow functions are always anonymous. These function expressions are best suited for non-method functions and they can not be used as constructors.

A Note on How this Works in Arrow Functions

One of the most handy features of an arrow function is buried in the text above:

An arrow function… lexically binds the this value (does not bind its own this…)

What this means in simpler terms is that the arrow function retains the this value from its context and does not have its own this. A traditional function may bind its own this value, depending on how it is defined and called. This can require lots of gymnastics like self = this;, etc., to access or manipulate this from one function inside another function. For more info on this topic, see the explanation and examples in the Mozilla documentation.

Example Code

Example (also from the docs):

var a = [
  "We're up all night 'til the sun",
  "We're up all night to get some",
  "We're up all night for good fun",
  "We're up all night to get lucky"
];

// These two assignments are equivalent:

// Old-school:
var a2 = a.map(function(s){ return s.length });

// ECMAscript 6 using arrow functions
var a3 = a.map( s => s.length );

// both a2 and a3 will be equal to [31, 30, 31, 31]

Notes on Compatibility

You can use arrow functions in Node, but browser support is spotty.

Browser support for this functionality has improved quite a bit, but it still is not widespread enough for most browser-based usages. As of December 12, 2017, it is supported in current versions of:

  • Chrome (v. 45+)
  • Firefox (v. 22+)
  • Edge (v. 12+)
  • Opera (v. 32+)
  • Android Browser (v. 47+)
  • Opera Mobile (v. 33+)
  • Chrome for Android (v. 47+)
  • Firefox for Android (v. 44+)
  • Safari (v. 10+)
  • iOS Safari (v. 10.2+)
  • Samsung Internet (v. 5+)
  • Baidu Browser (v. 7.12+)

Not supported in:

  • IE (through v. 11)
  • Opera Mini (through v. 8.0)
  • Blackberry Browser (through v. 10)
  • IE Mobile (through v. 11)
  • UC Browser for Android (through v. 11.4)
  • QQ (through v. 1.2)

You can find more (and more current) information at CanIUse.com (no affiliation).

3

  • 4

    TypeScript also seems to support it.

    – mtyson

    May 1, 2017 at 19:39

  • 1

    It looks like this is a lambda expression, yes?

    – Addem

    Aug 30, 2018 at 22:22

  • 1

    Wanted to mention in terms of browser compatibility I use ES6/ES7 arrow functions and other features not compatible with IE11 natively but I use Gulp or Webpack along with Babel to transpile ES6 to ES5 so it works in IE11. So if you need IE11 support and you don’t mind setting up Babel then go for it.

    – mbokil

    Nov 4, 2019 at 20:16


86

That’s known as an Arrow Function, part of the ECMAScript 2015 spec

var foo = ['a', 'ab', 'abc'];

var bar = foo.map(f => f.length);

console.log(bar); // 1,2,3

Shorter syntax than the previous:

// < ES6:
var foo = ['a', 'ab', 'abc'];

var bar = foo.map(function(f) {
  return f.length;
});
console.log(bar); // 1,2,3

DEMO

The other awesome thing is lexical this… Usually, you’d do something like:

function Foo() {
  this.name = name;
  this.count = 0;
  this.startCounting();
}

Foo.prototype.startCounting = function() {
  var self = this;
  setInterval(function() {
    // this is the Window, not Foo {}, as you might expect
    console.log(this); // [object Window]
    // that's why we reassign this to self before setInterval()
    console.log(self.count);
    self.count++;
  }, 1000)
}

new Foo();

But that could be rewritten with the arrow like this:

function Foo() {
  this.name = name;
  this.count = 0;
  this.startCounting();
}

Foo.prototype.startCounting = function() {
  setInterval(() => {
    console.log(this); // [object Object]
    console.log(this.count); // 1, 2, 3
    this.count++;
  }, 1000)
}

new Foo();

DEMO

MDN
More on Syntax

For more, here’s a pretty good answer for when to use arrow functions.

1

29

These are Arrow Functions

Also known as Fat Arrow Functions. They’re a clean and consise way to write function expressions, e.g. function() {}.

Arrow Functions can remove the need of function, return and {} when defining functions. They are one-liners, similar to Lambda Expressions in Java or Python.

Example with no parameters

const queue = ['Dave', 'Sarah', 'Sharon'];
const nextCustomer = () => queue[0];

console.log(nextCustomer()); // 'Dave'

If multiple statements need to be made within the same Arrow Function, you need to wrap, in this example, queue[0] in curley brackets {}. In this case the return statement cannot be omitted.

Example with 1 parameter

const queue = ['Dave', 'Sarah', 'Sharon'];
const addCustomer = name => {
  queue.push(name);
};

addCustomer('Toby');

console.log(queue); // ['Dave', 'Sarah', 'Sharon', 'Toby']

You can omit {} from the above.

When there is a single parameter, the brackets () around the parameter can be omitted.

Example with multiple parameters

const addNumbers = (x, y) => x + y

console.log(addNumbers(1, 5)); // 6

A useful example

const fruits = [
    { name: 'Apple', price: 2 },
    { name: 'Bananna', price: 3 },
    { name: 'Pear', price: 1 }
];

If we wanted to get the price of every fruit in a single array, in ES5 we could do:

fruits.map(function(fruit) {
    return fruit.price;
}); // [2, 3, 1]

In ES6 with the new Arrow Functions, we can make this more concise:

fruits.map(fruit => fruit.price); // [2, 3, 1]

Additional information on Arrow Functions can be found here.