1

What is the point of using the spread operator as parameter inreturn withDefaultStatus(...)?

I've been staring and poking at this code for a while now and i can't figure something out.
At first i thought it's used as a condition, but now i'm totally confused.

PS1: I don't think it has anything to do with lodash, but i added it anyway.
PS2: The state is being passed from a React Component.

const {defaults} = require('lodash/fp')

const withDefaultStatus = defaults({
    isFinished: false,
    isPending: true,
    code: 0
});

const state = {
    isFinished: true,
    isMutation: false,
    isPending: false,
    lastUpdated: 1512730452993,
    queryCount: 5,
    status: 1,
    url: "https://",
}

function selectQueryStatus(state) {
    const {
        isFinished,
        isPending,
        status: code,
        lastUpdated,
        queryCount
    } = state || {};

    return withDefaultStatus({
        isFinished, isPending , ...code && { code, lastUpdated, queryCount }
    });
}

console.log(selectQueryStatus(state))
//output { isFinished: true, isPending: false, code: 1, lastUpdated: 512730452993, queryCount: 5 }
Vikas Yadav
  • 3,094
  • 2
  • 20
  • 21
Cristian Muscalu
  • 9,007
  • 12
  • 44
  • 76
  • 1
    @ShubhamKhatri why was this closed as a dupe? OP is asking **why** spread is used, **not what** it is. He even identified "the three dots" as a spread operator, so why dupe it to a post asking what `...` is? – Chris Dec 08 '17 at 11:48
  • @Chris, the post does explain, what does it do which will answer as to why is it there. If you don't agree, I will remove the duplicate vote – Shubham Khatri Dec 08 '17 at 11:50
  • @ShubhamKhatri Hmm, I don't think it really does. Anyway, when closing posts as dupes, don't link them to another dupe post. You might want to increase visibility to your own answers, but please use the canonical answer instead. – Chris Dec 08 '17 at 11:51

1 Answers1

2

In the following syntax

withDefaultStatus({
        isFinished, isPending , ...code && { code, lastUpdated, queryCount }
    });

The reason why Spread syntax is used is because, code, lastUpdate and queryCount values need to be passed to the object only when code is available. So essentially …code && { code, lastUpdated, queryCount } will return code, lastUpdated, queryCount when code is evaluated to true. And hence you entire object will become

 {
    isFinished,
    isPending ,
    code,
    lastUpdated,
    queryCount 
 }
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400