Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Should function declaration in catch be allowed? #131

Closed
davidpfahler opened this issue May 10, 2015 · 2 comments

Comments

@davidpfahler
Copy link

commented May 10, 2015

I got Move function declaration to function body root. error for the following code:

initialise()
function initialise () {
  try {
    return nativeImplementation()
  } catch (e) {
    function fakeImplementation () {
      // ...
    }

    return fakeImplementation()
  }
}

I was intentionally declaring the fakeImplementation function in the catch block, because I though it to be a waste to declare the function if it is most likely never being used. Isn't this an anti-pattern?

@dcousens dcousens added the question label May 12, 2015

@julien-f

This comment has been minimized.

Copy link

commented May 12, 2015

Function declarations are hoisted (automatically moved to the top of the scope) so your fakeImplementation() function is always created.

What you want is to use a function expression assigned to a variable:

initialise()
function initialise () {
  try {
    return nativeImplementation()
  } catch (e) {
    var fakeImplementation = function () {
      // ...
    }

    return fakeImplementation()
  }
}
@feross

This comment has been minimized.

Copy link
Member

commented May 13, 2015

What @julien-f said is correct. The error message could be more helpful, but I think we should keep this rule in place. I'm going to close this issue. Feel free to continue discussing if you want.

@feross feross closed this May 13, 2015

@lock lock bot locked as resolved and limited conversation to collaborators May 11, 2018

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
4 participants
You can’t perform that action at this time.