Search code examples
javascriptspread-syntax

Which role does the order of object spread and other properties play?


Consider an object data.

data = {
  draggingTaskId: '',
  entities: {},
  selectedTaskIds: [],
}

I am using destructuring assignment in two different orders, but the behaviour is different both the times. Does order matter in Object destructuring assignment?

console.log('----------------------------------');

console.log({
  ...data,
  draggingTaskId: "task-0",
});

console.log({
  draggingTaskId: "task-0",
  ...data,
});

console.log('----------------------------------');

Output:

--------------------------------

draggingTaskId: "task-0"
entities: {}
selectedTaskIds: []

draggingTaskId: ""
entities: {}
selectedTaskIds: []

-----------------------------------

In the second instance, the draggingTaskId is coming out as an empty string.


Solution

  • The order is indeed relevant - items that appear later override items that appear earlier, if they have the same keys.

    console.log({
      ...data,
      draggingTaskId: 'task-0', // this overrides the value of data.draggingTaskId = '', resulting in 'task-0'
    })
    console.log({
      draggingTaskId: 'task-0', // In this case this key is overridden by the value of data.draggingTaskId = '', resulting in ''
      ...data,
    })
    

    You may find this helpful - https://dmitripavlutin.com/object-rest-spread-properties-javascript/#21-object-spread-rule-latter-property-wins