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 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')
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:
this.dropDownFilter
has been assigned an anonymous function, which has a values
argument..filter()
method has an anonymous function and that returns the filtered value.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' })
}
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:
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