0

I am new to typescript and getting confused using => arrow. Can anyone please explain the meaning of the following javascript code:

  this.dropDownFilter = values => values.filter(option => option.value !== 'Others')
i alarmed alien
  • 9,412
  • 3
  • 27
  • 40
Anna
  • 1,669
  • 7
  • 38
  • 63

3 Answers3

1

If you go to docs for the fat arrow syntax. You can see various types like:

arg => console.log(arg); // <-- () not required if you have just one argument
(a, b) => console.log(a,b); // <-- () is required because of two arguments
arg => { return arg; } // <-- return statement is required within {}
(a, b) => { return a+b; } // <-- return statement is required within {}

this.dropDownFilter = values => values.filter(option => option.value !== 'Others')

One other advantage is that it has lexical this built in. So, you don't have to store this in any variable to use it in the function.


This is as same as this:

this.dropDownFilter = function(values) {
  return values.filter(function(option) {
    return option.value !== 'Others'
  })
}

If you see:

  1. this.dropDownFilter has been assigned an anonymous function, which has a values argument.
  2. then in the fat arrow syntax has a implicit return statement.
  3. In the inner .filter() method has an anonymous function and that returns the filtered value.
Jai
  • 74,255
  • 12
  • 74
  • 103
1

Since you don't use arrow functions special way to handle scope, this would be the same as:

this.dropDownFilter = function(values){
  return values.filter(function(option){ return option.value !== 'Others' })
}
0

This is syntax describing a function, where the arguments are on the left of =>, and the function body is on the right of =>. Two syntactical observations to make:

  1. The arguments are usually enclosed in parentheses as you may be accustomed to seeing in normal function syntax, but when there is only one arg, the parens are optional, as you see in the code you posted.
  2. When only one JS statement follows the arrow (as seen in your code), that statement is the return statement of the function. If multiple statements will be executed, then the function body must be enclosed in {} and the return keyword must be explicitly used.

Example:

function myFunc (arg1) {
  return arg1
}

is equivalent to:

var myFunc = arg1 => arg1

and also the same as

var myFunc = (arg1) => {
  return arg1
}

There are other considerations, such as the this context (arrow functions don’t really have this) and the arguments keyword (also not available in arrow functions), but I would be above my pay grade trying to get into that here. Here is MDN on that if you’re interested: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Ben Steward
  • 2,338
  • 1
  • 13
  • 23