2

what is the syntax of

then((response) => response.json())

in javascript?

I have googled a lot, but not find the explanation of => .

Damon Yuan
  • 3,683
  • 4
  • 23
  • 31

1 Answers1

1

These are known as Arrow function. An example:

// ES5
var selected = allJobs.filter(function (job) {
  return job.isSelected();
});

// ES6
var selected = allJobs.filter(job => job.isSelected());

You can find more detailed explanation at ES6 In Depth: Arrow functions.

Syntax:

If you are passing one paramter then it is like

var x = i=> i;

// which is equivalent to:

var x= function(i) {
    return i;
};

Also note that there is no explicit return statement in your arrow function then too it is going to return the argument which is passed in it.

Now if you are passing two parameters something like this:

var x= (i1, i2) => i1 + i2;

// which is equivalent to:

var x= function(i1, i2) {
    return i1 + i2;
};

In this case you need to pass the two arguments inside the paranthesis.

If your function is not having any argument then you need to put the empty braces like this:

var x = () => 1 + 2;

// which is equivalent to:

var x = function() {
    return 1 + 2;
};
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • This is very helpful, but is missing one thing. In his example (which I think comes from the react-native tutorial - so there will be lots of people looking for this!) there are parens around the input parameter. What does that mean? – GreenAsJade Oct 18 '15 at 04:34
  • I see now: it is a strange use of the syntax for providing more than one argument - it is a list of one argument to the arrow function. – GreenAsJade Oct 18 '15 at 04:37