4 ms·
An example case where "var" method is useful: function make_dot_product(dim) { if (dim === 3) { var dot = function(a,b) { retur
by yiransheng 12y ago
An example case where "var" method is useful:
function make_dot_product(dim) {
if (dim === 3) {
var dot = function(a,b) {
return a.x*b.x+a.y*b.y+a.z*b.z
}
} else if (dim === 2) {
var dot = function(a,b) {
return a.x*b.x+a.y*b.y
}
}
return dot
}
vs.
function make_dot_product(dim) {
if (dim === 3) {
function dot(a,b) {
return a.x*b.x+a.y*b.y+a.z*b.z
}
} else if (dim === 2) {
function dot(a,b) {
return a.x*b.x+a.y*b.y
}
}
return dot
}
The second case is erroneous, as it will always return 2-dimensional dot function (even if you call make_dot_product(20)). The is because function nameSpace() is defined at parse time, so inside the make_dot_product scope, two instance of dot functions are created, with the second overwriting the first. If we use var f = function() {...} this can be avoided.
- gnaritas 12y agoNot really a good case for var function make_dot_product(dim) { if (dim === 3) { return function(a,b) { return a.x*b.x+a.y*b.y+a.z*b.z } } else if (dim === 2) { return function(a,b) { return a.x*b.x+a.y*b.y } } return null; }
- jonahx 12y agoNot a great counterexample imo: function make_dot_product(dim) { return (dim === 3) ? dot3 : dot2; function dot3(a,b) { return a.x*b.x+a.y*b.y+a.z*b.z } function dot2(a,b) { return a.x*b.x+a.y*b.y } }
- Cthulhu_ 12y agoI think I prefer this one, although I'd put the return at the bottom for convention's sake. A lot of people don't know - or want or need to know - about the specifics of hoisting and what-have-you, and will consider this counter-intuitive.
- yawboakye 12y agoSweet combination of hoisting and scope creation. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- codeflo 12y agoI don't like using var in that way, because it seems like you're declaring two distinct variables. In your example, I'd much prefer: function make_dot_product(dim) { var dot; if (dim === 3) { dot = function(a, b) { return a.x * b.x + a.y * b.y + a.z * b.z; }; } else if (dim === 2) { dot = function(a, b) { return a.x * b.x + a.y * b.y; }; } return dot; } This also makes it clearer what happens if neither dim is neither 2 nor 3.
- jackweirdy 12y agoThe variables are the same. Var statements get hoisted to the beginning of the function. That said, it is cleaner to only 'var' each variable once, to suppress this confusion.