Home > Net >  Javascript Spread Operator used with return
Javascript Spread Operator used with return

Time:11-19

I'm confused on how the spread operator is being used here. I have a basic understanding of how the spread operator works but I'm confused on what the spread operators are referring to, how it is being used, and what it is offering. The "userCanDecline" const is a boolean retrieved from an above call. Please let me know if I can provide any more information about what I've shared.

return [
                ...(userCanDecline
                    ? [
                          {
                              label: 'Decline Draw',
                              icon: 'ban',
                              action: () => (el, ev) => {
                                  Service.decline(this.onCloseView);
                              },
                          },
                      ]
                    : [])

CodePudding user response:

Spread syntax can be used when all elements from an object or array need to be included in a list of some kind.

let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1 = [...arr1, ...arr2];

In your question, what's happening is that, userCanDeclined is checked if its value is true, if so, return an array in which the array below is spread(its values copied into the new returned array)

 [
  { 
    label: 'Decline Draw',
    icon: 'ban',
    action: () => (el, ev) => {
           Service.decline(this.onCloseView);
        },
   }
  ]

Else, spread or copy an empty array if false

  []
  • Related