52
u/Dethstroke54 Mar 29 '21 edited Mar 29 '21
The longhand example is a bit odd. I really don’t think you should be declaring and assigning separately for no reason.
Regardless if the shorthand is appropriate another way is
let a = 5, b = 8, c = 12Which makes for a better comparison, and in this case is imo clearer for assigning just a few simple values
11
u/ex-igne-vita Mar 29 '21 edited Mar 29 '21
Your example is both shorter and (significantly) more memory efficient than the shorthand example.
Edit: after actually testing this I discovered that I was in fact wrong about memory efficiency. Somehow, at least in whatever version of Node I’m running, destructuring actually used less heap and RSS than this example.
0
Mar 29 '21
[deleted]
4
u/ex-igne-vita Mar 29 '21
I am thinking something along the lines of allocation of some array and then its garbage collection.
That's exactly what I was thinking when I wrote that. Mentally stepping-thru the code, my assumption that the underlying c++ code would have to allocate an array, set values, allocate separate variables, set values to them, then destroy the array while re-setting the individual variables.
But, I may have been wrong in that assumption, because when I did some perf testing, the resident set size and external memory for each type of declaration were not as expected.
However, what was expected was that both memory usage and execution time were better when assign and declaring in 3 simple statements:
var a = 1; var b = 2; var c = 3;6
u/SoBoredAtWork Mar 29 '21
let [x, y, z] = [1, 2, 3]You're creating an array (
[1, 2, 3]) and allocating that to memory. We then assign x, y, and z to those array values. The array is never used, yet the JS engine has to create the array and store it somewhere, wasting both time and memory.0
Mar 29 '21
[deleted]
2
u/SoBoredAtWork Mar 29 '21
You're right. No one will ever notice the 30 milliseconds, or whatever, extra this takes. But the point is... why? This "code optimization", if that's what you call it, is almost completely worthless.
It's also not about the micro-optimization in execution time... but the fact that we should think about the affect (in time) certain data structures come with. Like, in the case of the guy who found that GTA load time was outrageous because an early developer used an array, when a map would've been much more efficient. We, as developers, should always have run time and how different structures affect run time in the back of our minds.
0
Mar 29 '21
[deleted]
2
u/SoBoredAtWork Mar 29 '21
I fully agree with all of the above. Readability should always be #1.
I would never write hard-to-read code to save a couple milliseconds.
I guess my point is that writing the original code is still worthless. It's not any more readable than defining 3 variables (and is arguably less readable if a dev is unaware of destructuring) and it doesn't help performance. It's just a completely worthless thing to do.
5
u/haltmich Mar 29 '21
Yep. Not sure how the JS interpreter parses this, but in my mind there's some extra legwork done in the first example because it's assigning the variable twice: first to undefined, then to the value.
2
u/TheDownvotesFarmer Mar 30 '21
The shorthand has more legwork done, create arrays, iterate to assing the values, it is more in fact thats why it is called a shorthand, nothing better than assigning separatelly the variables.
let a = 1; let b = 2; let c = 3;1
u/backtickbot Mar 30 '21
1
u/Smyles9 Mar 30 '21
This definitely seems like the best way to do this if declaring and assigning multiple vars at once.
8
18
u/delventhalz Mar 29 '21
Eh. Not a fan. If I reviewed a PR with this, I would probably ask whoever it was to rewrite it like a normal person.
I am as susceptible to writing overly clever code as anyone, but if literally the only benefit of whatever you did is that you “saved” two lines of code? It’s probably not worth the confusion. Save it for a code golf competition.
0
Mar 29 '21
[deleted]
14
u/delventhalz Mar 29 '21
To be clear, I think functions which return tuples/arrays that get destructured are a totally fine pattern. The purpose there is not to save lines of code, but to effectively return multiple values from one function.
What I am responding to is the example above where three separate variable assignments are replaced with a single assignment destructing an array literal. That serves no purposes other than two save lines. It is, in my personal opinion, rather silly.
// Nice const [name, setName] = useState('Sue'); // Nice const name = 'Sue'; const age = 32; const occupation = 'programmer'; // Silly const [name, age, occupation] = ['Sue', 32, 'programmer'];2
7
u/NaosAntares Mar 29 '21
Yeah, but it's a React convention, the use case presented in the image is totally different
5
u/SoBoredAtWork Mar 29 '21
That's extremely different than what's happening in the example.
0
Mar 29 '21
[deleted]
4
u/SoBoredAtWork Mar 29 '21
Right. In the example posted, it's creating a worthless array, only to use destructuring, to assign local variables. It's 100% worthless. Just assign the variables as variables are normally assigned.
In React, we call a function (this is important) that returns an array of 2 values. We then destructure so we can use said variables later.
It's a completely different scenario. Case 1 is completely worthless, case 2 is using destructuring as it's intended to be used.
2
u/dgrips Mar 29 '21
I strongly prefer Vue's composition api version of that, which uses object destructuring rather than array, the key difference being that order doesn't matter.
At a larger level though a pattern for returning reactive data to use in a template is different from just initializing variables, which I would not use either for.
1
u/Smyles9 Mar 30 '21
The shorthand seems like it could get confusing if you set too many variables at once, however it’s nice to know of other options, thanks
1
1
u/JazzApple_ Oct 28 '21
Really feel this is bad advice. Just because you can, does not mean you should.
1
0
0
Mar 29 '21
[deleted]
11
u/A-Kuhn Mar 29 '21
I honestly would never use the short hand described above. As other users pointed out destructing arrays is very handy. I just would not create an array solely to destructure it to multiple variables.
6
u/Dragotic-PS Mar 29 '21
Why would anyone want to use the "short-hand"?
You can destructure an array returned by an API method to store the contents in different variables.
Let's say a function returns an array: ["/", "cmd" "hello"]
Now you can simply separate the three via,
const [cmdToken, cmd, arg] = commandParser();
3
u/T_O_beats Mar 29 '21
Let’s say you’re making a game and you have an array of player objects.
const players = [{name: ‘p1’},{name:’p2’}]
Instead of working with array indexes you could use
const [player1, player2] = players.
Pardon the formatting.
2
u/ricealexander Mar 30 '21
Array destructuring is useful when you have an existing array, which you might get from an API call or from a function or object.
That might look like this:
function getCoordinates () { // do complex logic to get the coordinates and return them // coordinates might return as an array like [32, 86, 15] } // The Traditional Way let coordinates = getCoordinates(); let x = coordinates[0]; let y = coordinates[1]; let z = coordinates[2]; // Array Destructuring let [x, y, z] = getCoordinates()In this example, we called a function that returned an array, so the destructuring assignment saves us a few lines of code.
OP's example isn't as useful because they aren't getting the array from somewhere else, they are creating a new array just to destructure it, which is kind of pointless.
Free Code Camp has some more examples of destructuring: How to Use Array and Object Destructuring in JavaScript
1
u/Pearauth Mar 30 '21
This shorthand isn't really a shorthand as much as it is a side-effect of array destructuring.
This is more the kind of stuff you'll see using this syntax.
Swapping 2 variables e.g.
[a, b] = [b,a]Batching async calls to query data from db/server all at once. e.g.
const [resultA, resultB] = await Promise.All([requestA(), requestB()])Getting the first few of an array. e.g.
const [first, second, third, ...rest] = someLongArrayWhere I work we see this a lot more on the frontend
-1
u/urgent_detergent Mar 30 '21
You would never want to assign random numbers to variables. You would also never want to have short, undescriptive variable names like this either.
0
Mar 29 '21
[deleted]
8
u/SoBoredAtWork Mar 29 '21
This guy posts snippets like this a lot - and most of the time they're not very good (either are less readable or slower / require more memory). Point is, read the comments too, usually someone points out how whatever is posted is bad practice.
0
Mar 29 '21
[deleted]
4
u/SoBoredAtWork Mar 29 '21
Note: I agree. I love this format of post and would love to see more like it.
Unfortunately, the guy seems to be a beginner or mid-level (at best) and often just posts random "tricks" he comes across without really thinking much about whether or not it's a good idea. Or he just comes up with really poor examples of what he's trying to demonstrate.
Sometimes they're good posts, but not always. Check the comments for the real tips :)
138
u/ricealexander Mar 29 '21
Nothing wrong with