Skip to content

Instantly share code, notes, and snippets.

@joshcox
Created October 30, 2017 00:56
Show Gist options
  • Save joshcox/5dcf7c7f33d1078bc8aec75bfcaaf31e to your computer and use it in GitHub Desktop.
Save joshcox/5dcf7c7f33d1078bc8aec75bfcaaf31e to your computer and use it in GitHub Desktop.
js-things.md

JavaScript Things

Methods for building arrays with conditional elements

Assuming the following variables:

const showFoo = false;
const showBar = true;

Use an intermediate variable to conditionally push values

const arr = [];

if (showFoo) {
    arr += "foo";
}

if (showBar) {
    arr += "bar";
}

return arr;

Use the spread operator to conditionally sprinkle in values

// [...[]] === []
// [...[a], ...[b]] === [a, b]
return [
    ...(showFoo ? ["foo"] : []),
    ...(showBar ? ["bar"] : [])
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment