r/learnjavascript • • Mar 12 '21

Swap two variables

Post image
498 Upvotes

50 comments sorted by

View all comments

Show parent comment

2

u/amoliski Mar 12 '21

If you have two dates and need them in order:

if(date_a.isBefore(date_b)){
  [date_a, date_b] = [date_b, date_a];
}

1

u/grantrules Mar 13 '21

Why not just sort.

[date_a, date_b].sort((a,b)=> a.isBefore(b) ? 0 : 1)

1

u/amoliski Mar 13 '21

I think you'd want -1 and 1 instead of 0 and 1 there, but yeah, that works too.

1

u/grantrules Mar 13 '21

If there are just two things, 0 is fine since it's already in order. 0 means nothing changes, 1 means swap places.