1

What is the purpose of this javascript code structure?:

var GivenArrayOfJobs = () => {
    var selectedJob: WorkerModels.JobDetailsResponseModel = {
        JobId: "25c63b12-9e37-4be0-a8af-4cf237766317",
        WorkerId: "56e63b12-9e37-4be0-a8af-4cf237766317"
    };
    return selectedJob;
}

Specifically, I'm not sure what the following syntax indicates or its advantage over a more traditional js implementation:

var GivenArrayOfJobs = () => {
Greg Brattle
  • 421
  • 1
  • 7
  • 20
  • 2
    `() => {} ≡ function(){}.bind(this)` – elclanrs Mar 09 '16 at 18:38
  • This is ES6/2015 syntax. Learn it. Love it. – Bosworth99 Mar 09 '16 at 18:42
  • 3
    Possible duplicate of [Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?](http://stackoverflow.com/questions/34361379/arrow-function-vs-function-declaration-expressions-are-they-equivalent-exch) – Evan Davis Mar 09 '16 at 18:42
  • 2
    This part doesn't look like legal syntax: `var selectedJob: WorkerModels.JobDetailsResponseModel = {...}` unless it's something new I've never seen before. – jfriend00 Mar 09 '16 at 18:43

2 Answers2

3

This syntax is called arrow functions and are new in ES2015 specification.

One obvious advantage is that there is slightly less code to write.

Also, arrow functions are lexically scoped and so if you use this inside and arrow function it is bound to the lexical container. In some scenarios this reduces the need to explicitly bind the context (e.g. .bind(this)).

In your example, there is not much difference (in scoping) because this is not used, but the syntax is (subjectively) a bit nicer.

Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
  • In this particular example, what is the advantage of the arrow function over a basic js variable like this: var GivenArrayOfJobs = selectedJob.WorkerModels.JobDetailsResponseModel = { JobId: "25c63b12-9e37-4be0-a8af-4cf237766317", WorkerId: "56e63b12-9e37-4be0-a8af-4cf237766317" }; – Greg Brattle Mar 09 '16 at 19:17
1

It is Ecmascript 6 arrow function. It is very similar to anonymous functions except that it will bind its lexical scope into it automatically. And that bound scope cannot be modified via call/apply or any further .bind(obj)

Arrow function implementation:

var GivenArrayOfJobs = () => {
    selectedJob.WorkerModels.JobDetailsResponseModel = {
        JobId: "25c63b12-9e37-4be0-a8af-4cf237766317",
        WorkerId: "56e63b12-9e37-4be0-a8af-4cf237766317"
    };
    return selectedJob;
}

Anonymous function implementation:

var GivenArrayOfJobs = function(){
    selectedJob.WorkerModels.JobDetailsResponseModel = {
        JobId: "25c63b12-9e37-4be0-a8af-4cf237766317",
        WorkerId: "56e63b12-9e37-4be0-a8af-4cf237766317"
    };
    return selectedJob;
}.bind(this);
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130