Skip to content

Instantly share code, notes, and snippets.

@jashkenas
Created November 23, 2011 21:23
Show Gist options
  • Save jashkenas/1389969 to your computer and use it in GitHub Desktop.
Save jashkenas/1389969 to your computer and use it in GitHub Desktop.
// How do you tend to declare variables in your code, when nested in an if / else?
// All three are functionally equivalent.
// (Ternary is cheating for these purposes.)
// Option 1:
function() {
if (condition) {
var attrs = a;
} else {
var attrs = b;
}
}
// Option 2:
function() {
var attrs;
if (condition) {
attrs = a;
} else {
attrs = b;
}
}
// Option 3:
function() {
if (condition) {
var attrs = a;
} else {
attrs = b;
}
}
@andrewvc
Copy link

var res = (function () {
  if (condition) {
    return a;
  } else {
    return b;
  })();

(Just kidding, I'm all about #2)

@JasonOffutt
Copy link

Crockford will destroy you with his mind if you choose 1 or 3.

@johnjbarton
Copy link

Every JS dev knows in the heart #1 should be the right answer. #2 is C and #3 is asking for trouble.

@narfdotpl
Copy link

#2

@sumitngupta
Copy link

el numero dos.

@fat
Copy link

fat commented Nov 24, 2011

@andrewvc

var res = (function () {
  if (condition) return a
  return b
}())

@anthonywu
Copy link

#2

@ricardobeat
Copy link

@fat that's so pretty

 var a = (function(){ return 'value'; }).call(this);

@andrewvc
Copy link

@fat I never, ever, leave braces off when optional in JS. I'll take the line-noise for security. if w/o braces only works when it's at the end of a line a la Ruby.

@jxson
Copy link

jxson commented Nov 24, 2011

#2

@fat
Copy link

fat commented Nov 24, 2011

I never, ever, leave braces off when optional in JS

@andrewvc

http://i.imgur.com/NaI4O.gif

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment