0

What does the "=>" operator do in Javascript? This is probably a very basic question, but it is ungoogle-able. Does this operator have a name (to help me find it in references)? It seems to be some kind of remapping function. An example of where I've found it:

let maxLen = Math.max.apply(null, arrays.map(v => v.length)), out = [];

for finding the longest array held in arrays.

OliverD
  • 1,074
  • 13
  • 19
  • It's a fancy new shorthand for functions introduced in ES6! `function(a){ return a * 2; }` becomes `a => a * 2`, which is much easier to read for small functions. – somethinghere Nov 03 '15 at 11:48
  • 2
    I typed `ES6 => function` in google and this is the first link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions. "ungoogle-able" is completely false. – Claies Nov 03 '15 at 11:49
  • @somethinghere: There are major differences beyond brevity. – T.J. Crowder Nov 03 '15 at 11:50
  • @Claies that would depend on you knowing already it was ES6 and to do with functions. Google "JavaScript => operator" and see how far you get – OliverD Nov 03 '15 at 15:06

2 Answers2

2

They are called arrow functions. It's an alternate way of defining a function introduced in Ecmascript 6.

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.

You example is equivalent to:

let maxLen = Math.max.apply(null, arrays.map(function(v){ return v.length; })), out = [];

There is an in depth explanation of arrow functions here, which explains them far better than I can.

James Brierley
  • 4,630
  • 1
  • 20
  • 39
1

This is a ES6 shortcut, it means:

arrays.map(function ( v ) {
    return v.length;
});

With the arrow you can execute a statement, like in your example, or a code block:

arrays.map(v => {
    // do something long with v
    return theValue;
});
TheGr8_Nik
  • 3,080
  • 4
  • 18
  • 33