Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Spread Operator used with return

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);
                              },
                          },
                      ]
                    : [])
like image 786
Max Taylor-Hayden Avatar asked Sep 05 '26 10:09

Max Taylor-Hayden


1 Answers

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];
const 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

  []
like image 94
Maye Edwin Avatar answered Sep 08 '26 09:09

Maye Edwin