Tom Bird Tom Bird - 1 year ago 44
Javascript Question

Name or term of javascript syntax for function without function text?

I've been using a new method that I just learned for keeping outside scope inside of another function but I can't remember the term for the syntax used. Below is an example of how it works:

Api.get().then( (data) => {
console.log('do something with data', data);
}, ( e ) {
console.log('Error: ', e );

Basically, its a callback function but what is the term or name of this type of syntax. The reason I like using this is because you can still reference
and its values and methods, whereas using
function( data )
would lose
context. I want to know the name or term of this syntax because it doesn't seem to be supported by iphone or safari and I would like to look further into support and documentation on support for this method.

Answer Source

It's an arrow function and it's part of the latest 6th Edition of the ECMAScript standard (Also called ECMAScript 2015 since it was released in 2015). It's not as well supported by many browsers as you can see here.

You can use them in older browsers using something called a transpiler, which in essence all it does is convert ECMAScript 6 code (which isn't all that well supported) into more compatible ECMAScript 5 code. There are many, but Babel is the most popular one. You can try it out here and watch how arrow functions transform into compatible, ECMAScript 5 code that works across all browsers.

The reason I like using this is because you can still reference this and its values and methods

You can get the same results that arrow functions give you using bind(). Try this:

Api.get().then(function(data) {
   console.log('do something with data', data);
}.bind(this), function(e) {
   console.log('Error: ', e );

What bind() does is it creates a new function that sets whatever object you send to it as the first parameter, to this. This way you can still get access to the current scope you are working on. You can read more about bind() here.

I hope this answers your question.