Skip to content

Instantly share code, notes, and snippets.

@qubyte
Last active December 31, 2015 03:18
Show Gist options
  • Save qubyte/7926250 to your computer and use it in GitHub Desktop.
Save qubyte/7926250 to your computer and use it in GitHub Desktop.
The behaviour of `return` when used with `new`.

Here is a regular constructor function:

var Hello = function (name) {
    this.name = name;
};

When used with new, you get what you would expect:

new Hello('Mark'); // { name: Mark } and hello.constructor is [Function Hello] etc.

Let's modify the constructor to be a bit more explict. If no return is given in a JS function, undefined is implied.

Hello = function (name) {
    this.name = name;
    return undefined;
};

new Hello('Mark'); // Exactly the same as before.

That's a little weird when you think about it. We're telling it to return undefined but we get an object instead. It's tempting to think at this point that the return simply gets ignored when using new, but that's not entirely true. In fact, this only applies to primitive types (null, undefined, numbers, string and booleans). When you return a reference type (functions, objects, arrays etc.) the return is not ignored!

Hello = function (name) {
    this.name = name;
    
    return [0, 1, 2, 3, 4, this.name];
}

new Hello('Mark'); // [0, 1, 2, 3, 4, 'Mark']

It's very hard to see a case for which returning like this is actually useful. Some arcane applications may exist though. If you can think of something, please leave a comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment