What kind of function is this?

Viewed 56

Recently I saw this functon. I mean specifically this line/syntax:

export const selectItemBySpecificId = (id: string):any => createSelector(

What kind of function is this?

I know functions like: function doSomething() { ... } // function delaration statement

let doSomething = function() { .. } // function expresion

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

Full example (it's a NgRx Selector with parameter):

export const selectItemBySpecificId = (id: string):any => createSelector(
    selectAllItems,
    (data: any) => {
        const result = data.filter((item: IItem) => iem.id === id);
        if (result.length >= 1) {
            return result[0];
        }
        return null;
    }
);
3 Answers

This is an arrow function written in TypeScript. At runtime, the types would be removed, and it would work similarly to export const selectItemBySpecificId = (id) => createSelector(...); or export function selectItemBySpecificId(id) { createSelector(...) }. In the editor or when using tsc, id: string will require the type of the id parameter to be a string, and : any means the function can return any typed and it won't be checked (like normal JS).

It's a arrow function

An arrow function expression is a compact alternative to a traditional function expression, but is limited and can't be used in all situations.

it's another way to define functions in js it has some difference is the way it handle (this) an other functionality of a js function read more about it in MDN docs to understand it better since you gonna use it a lot Read More

some of the key differences

  • Arrow functions don't have their own bindings to this, arguments or super, and should not be used as methods.
  • Arrow functions don't have access to the new.target keyword.
  • Arrow functions aren't suitable for call, apply and bind methods, which generally rely on establishing a scope.
  • Arrow functions cannot be used as constructors. Arrow functions cannot use yield, within its body.

Adding to the answers already given, we obviously have a higher order function createSelector that returns a function here:

const selectItemBySpecificId = (id) => createSelector(/* ... */);
//                                     ^^^^^^^^^^^^^^
//                          function that returns a function
Related