0

So my problem is the following:
I have the two functions
getDatesAndStringOfTimespan(timeSpan, goBack) returns {from, to}
limitFromAndTo(from, to, fromLimit, toLimit) returns {from, to}

I now want to do the following:
let { from, to } = getDatesAndStringOfTimespan(timeSpan, goBack)
{ from, to } = limitFromAndTo(from, to, fromLimit, toLimit)

But it says 'Declaration or statement expected.' I know I could do
let { from, to } = getDatesAndStringOfTimespan(timeSpan, goBack)
let object = limitFromAndTo(from, to, fromLimit, toLimit)
from = object.from
to = object.to

It just seems like there is a smarter way of doing this.

  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment – Teemu Aug 19 '21 at 14:45
  • If I understand it correctly, this would be the right way: `let { from, to } = getDatesAndStringOfTimespan(timeSpan, goBack); [ from, to ] = limitFromAndTo(from, to, fromLimit, toLimit)` But it still doesn't work – Robin Jehn Aug 19 '21 at 15:15

1 Answers1

0

I can see two other ways of doing this.

  1. Wrap the second assignment in parentheses to help the js compiler to understand what's happening (I'm not recommending this, just making your implementation possible in practice)
let { from, to } = getDatesAndStringOfTimespan(timeSpan, goBack);
({ from, to } = limitFromAndTo(from, to, fromLimit, toLimit))
  1. Only destructure the second values
const dates = getDatesAndStringOfTimespan(timeSpan, goBack)
const { from, to } = limitFromAndTo(dates.from, dates.to, fromLimit, toLimit)

I would prefer #2 in a code review, as it's clearer to see what's going on - no magic brackets, and more readable

seedBoot
  • 373
  • 2
  • 12
  • Thanks a lot!! In this case I will go for the second option, but this comes up in my code every now and then and sometimes I may consider the first one. Never really learned Javascript, just plain Java :/ – Robin Jehn Aug 19 '21 at 15:34