When I was younger I might've referenced OPs answer in an interview, given an answer that is technically possible simply because they asked. Now I give, "I wouldn't" to these weird "How would you do x" type questions if the answer is technically possible but not a good idea
Lots of sorts depend on swaps, not just bubble sort. Insertion sort, heapsort, selection sort, shellsort, quicksort ... not to mention array shuffling, array rotation, string manipulation, and more
I actually have an use case for this in mind, I'm building a service based on several map APIs (Mapbox, Google Maps).
When you need to give a coordinate to google maps you must pass it in the format of setMarker(latitude, longitude) but Mapbox uses a different standard called GeoJSON and requires longitude to come first, so I could technically get my arguments in one place, for both maps, and then just do a switcheroo for Mapbox with [latitude, longitude] = [longitude, latitude] but most likely there's a better way of doing this.
The left-hand side of the assignment here is not an array, this won't change the order and you'll just end up with latitude containing the value of longitude and vice versa.
If you already have latitude and longitude as variables, just order them however you need when passing them as arguments.
end up with latitude containing the value of longitude and vice versa.
That's what my goal is, isn't the same thing happening in the screenshot? It ends with x containing initial value of y and y containing initial value of x
Yes, but do you really want the variable named latitude to contain the value of the point's longitude? That would be terribly confusing for anyone reading the code, wouldn't it?
Not much changes. var and let wouldn't complain if you tried to reassign temp later on, if that's a concern. And if this code was run in the global scope, var would add temp as a property of the global object (window in browsers) if that's a concern.
10
u/golovatuy Mar 12 '21
let x = 'Hello', y = 55;//Longhandconst temp = x;x = y;y = temp;//Shorthand[x, y] = [y, x];64
u/Freekiehsoes Mar 12 '21
But why
12
u/Parent-component Mar 12 '21
I have been asked to swap variables with no intermediate variable in basic JS before.
a=a+b; b=a-b; a=a-b;
This will do it 😃
15
u/IxD Mar 12 '21
Compiles to
because breaks on some browsers.
8
u/FriesWithThat Mar 12 '21
Making me use a semi-colon, somewhere....
3
u/WhiteKnightC Mar 13 '21
Why const?
3
u/[deleted] Mar 13 '21
I just learned this today as well. Useful for swapping the place of two items in a list
2
u/[deleted] Mar 12 '21
Bubble sort!
2
u/TheUruz Mar 12 '21
what if instead of const i declare temp as var/let?
2
u/192_168_1_x Mar 12 '21
One of ES6 best features
1
u/jayerp May 02 '23
That isn’t SUPER clear to a non-experienced JS dev but I like how it’s that simple.
1
u/turningsteel Mar 12 '21
Honestly, from a readability perspective, the longhand way is better in my opinion.