Search code examples
javascriptstorybook

What is the reason for binding arrow function in javascript?


Going through the storybook documentation

essentially this part caught my eye:

const Template = (args) => ({
  //👇 Your template goes here
});

export const Primary = Template.bind({});

So I got curious, what is the reason for calling bind on an arrow function? I tried it and the only effect I've seen is that it is hiding the function implementation from toString.

Primary.toString()
> 'function () { [native code]  }'

Solution

  • It seems completely pointless at first, but it's a way to create a new function that does the same as the original one. In another example further down on that page, you can see

    const Template = (args) => ({
      //👇 Your template goes here
    });
    
    
    ArrayInclude = Template.bind({})
    ArrayInclude.parameters = { controls: { include: ['foo', 'bar'] } };
    
    RegexInclude = Template.bind({})
    RegexInclude.parameters = { controls: { include: /^hello*/ } };
    
    ArrayExclude = Template.bind({})
    ArrayExclude.parameters = { controls: { exclude: ['foo', 'bar'] } };
    
    RegexExclude = Template.bind({})
    RegexExclude.parameters = { controls: { exclude: /^hello*/ } };
    

    which creates multiple bound function objects from the same Template and assigns different .parameters to them.

    The same could be achieved with

    const Primary = Template.bind();
    const Primary = Template.bind(null);
    const Primary = (args) => Template(args);
    // etc