Jimbot
Jimbot

Reputation: 716

Javascript syntax of functions signature

In the documentation of styled from MUI, I came across this function signature:

styled(Component, [options])(styles) => Component

I found many examples with this syntax in the MUI demos.

It seams to me, I am lacking basic syntax knowledge, because I don't get the (styles) => Component part. I understand this is a lambda expression, but for me it's not part of the function signature, because it's not enclosed into the parenthesis.

Can someone explain, what it does and why it's different form a signature like

styled(Component, [options], (styles) => Component)

?

Upvotes: 1

Views: 345

Answers (2)

Marcello di Simone
Marcello di Simone

Reputation: 1653

This is an API description syntax, not actual JS code, where '=>' is used to describes what type of value is returned from the function (in this case an object of type Component). It's a bit confusing because it looks like a regular JS arrow function. The syntax before the arrow however is valid JS Code and describes a self invoking function. styled returns a function that can be immediately invoked by adding parentheses to the function call.

// example implementation of styled
const styled = function(component, options = {}) {
 return function(styles) {return new Component(styles)};
}

// long version of API description
const returnedFunction = styled(myComponent, options);
const returnedComponent = returnedFunction(styles);

// condensed version
const returnedComponent = styled(MyComponent)(styles);

Your provided example would not work, because your arrow function would be executed before the actual function call and only its return value (in your case Component) would be passed as third argument, the styles argument of the callback function itself would have no impact.

Upvotes: 1

Quentin
Quentin

Reputation: 943563

styled(Component, [options])(styles) => Component

If you're not familiar with the syntax used in that part of the documentation, then the example after the description is excellent.

styled is a function which takes two arguments (Component and, optionally, options).

It returns a function.

The returned function takes one argument (styles) and returns a Component.


Your version, by contrast:

styled(Component, [options], (styles) => Component)

Here, styled is a function which takes three arguments.

  • Component
  • options (which is marked as optional, but can't be because the third argument isn't marked as optional)
  • A function which takes one argument (styles) and returns a Component

The return value for styled is missing.

Upvotes: 4

Related Questions