Emerging JavaScript pattern: multiple return values
loige.co
loige.co
I also missed generators from this list, which are the "official" (but a lot more complex than the ones showed here!) way of having multiple async returns:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
I have been using it for awhile.
let [isValid, err] = validate(data)
It’s nice for a few reasons:1. I know anything returned `err` is safe to display back to the user
2. Using the array (as opposed to an object) can allow me to name the values when I destructure so it can be used multiple times in the same block with useful naming.
3. I can destructure just the first half `[isValid]` if that’s all I care about.
4. More generally it helps keep the code readable. Other control flows might rely on some casting, assumptions, or exceptions but this way presents a nice customizable api for users writing the code, and a readable api for those reviewing the code.
`cont [, err] = validate(data)`
Anything to make JS feel less haphazard and more elegant (i.e. using TypeScript) is awesome in my books. Looking forward to hopefully using this pattern in my personal work going forward, and maybe trying to introduce it to my team ta work.
https://docs.microsoft.com/en-us/dotnet/csharp/language-refe...
This is pretty hacky and it smells. it also won't work in languages like typescript (without losing the advantage of using it) which is frequently used.
I do absolutely not see the author advocating returning values in an array instead of an object, in fact, they seems to be saying the exact opposite? (starting with the array example, and then going to the object example afterwards)
The primary point of the article is the destructuring which makes the syntax much nicer.
It will work just fine in TypeScript, where you can define a "fixed size" array as a type:
type Test = [number, string];
const test: Test = [1, 'something'];
The second line will fail compilation if there's a different number of elements in that array, or if the types don't match.