0

So, I was reading through a js file the other day and noticed a very strange syntax for what I perceived to be a short-hand function definition. I thought it could possibly be related to a library of some kind but I coded up an example in JSFiddle using pure javascript and it does indeed work.

Has anyone seen this before? Could you point me to documentation for it so I could read a little more about it? What's the significance of the '>' symbol after the '='?

Sample:

() => {
  alert('hi');
}

And here's the code in use on JSFiddle

Funktr0n
  • 1,711
  • 2
  • 16
  • 23
  • 7
    You are looking at [Arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) which has limited availability across browsers at this point. Some precompilers like Typescript/Coffeescript does pollyfill them for ES5.. – PSL Feb 28 '15 at 19:47
  • FWIW, this function can be simplified to `() => alert('hi')` – Felix Kling Feb 28 '15 at 19:57

1 Answers1

2

It doesn't work in my browser (Chrome). Which probably means you're using Firefox. Mozilla is quick in implementing new Ecmascript features. Arrows are a feature of Ecmascript 6.

Arrows are a function shorthand using the => syntax. They are syntactically similar to the related feature in C#, Java 8 and CoffeeScript. They support both expression and statement bodies. Unlike functions, arrows share the same lexical this as their surrounding code.

You can read more about Ecmascript 6 features here: https://github.com/lukehoban/es6features

Edit: Since the native support for arrows is limited at this point, you might have encountered CoffeeScript in the js file you were reading through.

Kjell Ivar
  • 1,154
  • 8
  • 8