Skip to content

Instantly share code, notes, and snippets.

@cowboy
Last active June 4, 2023 05:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cowboy/b632222805cafce88e66d751bc42d5ea to your computer and use it in GitHub Desktop.
Save cowboy/b632222805cafce88e66d751bc42d5ea to your computer and use it in GitHub Desktop.
javascript / es2015: should functions returning multiple, separate values return an object or tuple (array)?
// This function returns 2 separate values via an object with 2 properties.
function returnTwoValuesObj(str) {
const length = str.length;
const hasSpaces = str.indexOf(' ') !== -1;
return {length, hasSpaces};
}
// This function returns 2 separate values via an array (effectively a tuple) with 2 items.
function returnTwoValuesTuple(str) {
const length = str.length;
const hasSpaces = str.indexOf(' ') !== -1;
return [length, hasSpaces];
}
// My questions:
// Which of the following would you rather write?
// If you don't like either of the following, how would you write it?
function withObj() {
const helloStr = 'hello';
const {length: helloLength, hasSpaces: helloHasSpaces} = returnTwoValuesObj(helloStr);
console.log(helloStr, helloLength, helloHasSpaces);
const helloWorldStr = 'hello world';
const {length: helloWorldLength, hasSpaces: helloWorldHasSpaces} = returnTwoValuesObj(helloWorldStr);
console.log(helloWorldStr, helloWorldLength, helloWorldHasSpaces);
}
function withTuple() {
const helloStr = 'hello';
const [helloLength, helloHasSpaces] = returnTwoValuesTuple(helloStr);
console.log(helloStr, helloLength, helloHasSpaces);
const helloWorldStr = 'hello world';
const [helloWorldLength, helloWorldHasSpaces] = returnTwoValuesTuple(helloWorldStr);
console.log(helloWorldStr, helloWorldLength, helloWorldHasSpaces);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment