-
-
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; | |
} | |
} |
2
Option 2
2
#2
function option4(){
var attrs = condition ? a : b
}
#2
option 4
We definitely need expression forms in JS for such cases. And not only with simple if
s which can be managed by ?:
op. But for all of them: if
, switch
, try
, blocks, etc. The discussion was/is here: https://mail.mozilla.org/pipermail/es-discuss/2011-November/018222.html
And for now, regarding JS, variant #2 is OK.
Dmitry.
#2
#2
@DmitrySoshinkov: Agreed. The point of option 4 above is that simple if
doesn't make good example for the topic. I personally use option 3 for similar cases.
try { var result = run() }
catch(e){ result = e }
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:
var fn = function (arr) {
for (var i = 0, l = arr.length; i < l; i++) {
// operations
}
};
var fn = function (arr) {
var args = [].slice.call(arguments),
i = 0,
l = arr.length;
for (; i < l; i++) {
// operations
}
};
@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
option #2