Reputation: 11763
Is there any difference when I explicitly return from a function vs. implicitly return?
Here's the code that puzzles me ATM:
function ReturnConstructor(arg){
// Private variable.
var privateVar = "can't touch this, return ctor.";
// This is what is being exposed to the outside as the return object
return {
print: function() {
console.log("ReturnConstructor: arg was: %s", arg);
}
};
}
function NormalConstructor(arg){
// Private variable.
var privateVar = "can't touch this, normal ctor";
// This is what is being exposed to the outside as "public"
this.print = function() {
console.log("NormalConstructor: arg was: %s", arg);
};
}
var ret = new ReturnConstructor("calling return");
var nor = new NormalConstructor("calling normal");
Both objects ('ret' & 'nor') seem the same to me, and I'm wondering if it's only personal preference of whomever wrote whichever article I've read so far, or if there's any hidden traps there.
Upvotes: 4
Views: 8110
Reputation: 115
Implicit return only happens for single statement arrow functions, except When arrow function is declared with {}, even if it’s a single statement, implicit return does not happen: link
Upvotes: 0
Reputation: 413737
When you use new
, there's an implicit value. When you don't use new
, there isn't.
When a function called with new
returns an object, then that's the value of the new
expression. When it returns something else, that return value is ignored and the object implicitly constructed is the value of the expression.
So, yes, there can be a difference.
Upvotes: 6