Created
November 23, 2011 21:23
-
-
Save jashkenas/1389969 to your computer and use it in GitHub Desktop.
This file contains 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
// 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; | |
} | |
} |
@mythz Ah, didn't realize that vars declared within a conditional branch that's never executed were still hoisted like that. Thanks.
Good reference: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting
@akavile, that reference is brilliant!! thx for sharing it!..
Option 2 all the way... will pass a jslint too.
#2
#2
#2
var res = (function () {
if (condition) {
return a;
} else {
return b;
})();
(Just kidding, I'm all about #2)
Crockford will destroy you with his mind if you choose 1 or 3.
Every JS dev knows in the heart #1 should be the right answer. #2 is C and #3 is asking for trouble.
#2
el numero dos.
var res = (function () {
if (condition) return a
return b
}())
#2
@fat that's so pretty
var a = (function(){ return 'value'; }).call(this);
@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.
#2
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If the only variables in the current scope are the ones created for a loop, then I will create them in the loop statement, otherwise it's single var at the top: