Last active
June 4, 2023 05:29
-
-
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 file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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