Skip to content

Instantly share code, notes, and snippets.

@jaredwilli
Forked from paulirish/gist:747835
Created November 21, 2011 17:37
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 jaredwilli/1383333 to your computer and use it in GitHub Desktop.
Save jaredwilli/1383333 to your computer and use it in GitHub Desktop.
`x || (x = y)` pattern for using an incoming value otherwise using some default
// from https://twitter.com/#!/LeaVerou/status/16613276313980929
// this pattern below is common for using an incoming value otherwise using some default.
/* Bad: */ x = x ? x : y; // simple ternary.
// if x is truthy lets use it.
/* Better: */ x = x || y; // logical OR.
// you could string a bunch of these easily to grab the first non-falsy value:
// x = x || y || z || a;
/* Best: */ x || (x = y); // right-hand assignment!
// done without the parens this would throw a syntax error.
// if x is truthy we don't even need to do the assigment,
// so the logical OR will bypass it.
// jslint especially hates that last one. big surprise.
// and of course, if x is intentionally supposed to be 0, false, or ''
// then you're fucked and you'll have to do something nasty like:
x = (x !== undefined) ? x : y; // yuck. (parens optional)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment