7

tl;dr: what does => do?

I've just finished solving a problem on codewars and after looking at other peoples' common responses to the problem, I keep seeing this: =>

The problem is below:

You have a quiver of arrows, but some have been damaged. The quiver contains arrows with an optional range information (different types of targets are positioned at different ranges), so each item is an arrow. You need to verify that you have some good ones left, in order to prepare for battle. The below is an example array which is the quiver of arrows.

anyArrows([
{range: 5}, 
{range: 10, damaged: true}, 
{damaged: true}
])

If an arrow in the quiver does not have a damaged status, it means it's new.

This is an example I saw which returns true or false, depending on if there is an undamaged arrow in the quiver:

function anyArrows(arrows){
  return arrows.some(a => !a.damaged);
}

Now, that was way shorter than my code! Mine was a lot more basic:

function anyArrows(arrows){
  for ( var i = 0 ; i < arrows.length ; i++ ){
    if ( arrows[i].damaged === false ) { return true; }
    else if (arrows[i].damaged === true) { return false; }
    else if (arrows[i].range === 0) { return false }
    else { return true; } 
  }
  if (arrows.length === 0) return false;
}

Again though, the question is: what does => do in this case and in general?

shilovk
  • 11,718
  • 17
  • 75
  • 74
  • 1
    [Arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) ? – Arun P Johny Sep 30 '15 at 12:25
  • It is the new short function syntax in ES6. E.g. `function(x){return x.Id;}` becomes `x => x.Id`. It is similar to lambda expressions in C#. – Sverri M. Olsen Sep 30 '15 at 12:27
  • That to me seems like a LINQ query, basically what they are doing is, return arrows where `a // is an object from arrows` is `!damaged`. Take a look at this https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/some – Canvas Sep 30 '15 at 12:28

1 Answers1

9

=> is ES2015 syntax that separates arrow function parameters from body, e.g. (params) => { /* body */ }.

ArrowFunction : ArrowParameters => ConciseBody

JMM
  • 26,019
  • 3
  • 50
  • 55