A friend of mine just asked me which of the following two expressions would be the better choice. While I understand the question, and thus the definition of better, is potentially a matter of opinion and thus off-topic; I was keen to understand if there was a good reasoning in favour of one.
var count = _.reduce(randomData, function(prefix, businessData){
return prefix + businessData.length;
}, 0);
return {
name: randomName,
pos: position[randomName],
count: count
};
or
return {
name: randomName,
pos: position[randomName],
count:
_.reduce(randomData, function(prefix, businessData){
return prefix + businessData.length;
}, 0)
};
Both another colleague and I were in agreement that the first one would be better as it's clearer, potentially easier to debug and more easily understood but outside of that we couldn't justify our choice.
Is there a reason why one would favour returning the value against returning the expression?
Is there a difference between returning a value and returning an expression in JavaScript?
No, you're returning a value either way. More accurately, from your code examples, you're assigning a value to the count
property of the object you're returning a reference to either way.
The only difference in your code examples is when reduce
is called. In the first one, it's called before the construction of the object you're returning begins. In the second, it's called during that construction. There's no difference in what the function then goes on to return, though.
Is there a reason why one would favour returning the value against returning the expression?
Since the first answer above is "no," the only reasons take us into, or at least very near, the land of opinion.
The closest objective measure I can come up with is one of the ones you pointed out: Debugging. With the first one, you can easily see count
before constructing and returning the object. With the second, that's more difficult.
More detail about this object construction thing, in case that was a surprise: JavaScript defines the order that the property initializers in an object initializer are run: Unsurprisingly, they're run in source-code order. So for instance, if we have this code:
var num = 0;
function foo() {
return ++num;
}
var obj = {
a: foo(),
b: foo(),
c: foo()
};
...we know for certain that the value of obj.a
is 1, obj.b
is 2, and obj.c
is 3. That's defined by the specification.