3

I'm asking this because I just saw it on a piece of code:

var myVar = function func(arg){
   console.log(arg);
}

I don't understand why function is "renamed" func just before it was defined for myVar.

Can somebody explain the interest of doing this, and not just:

var myVar = function(arg){
   console.log(arg);
}

Thank you very much!

3
  • If you run this, func is undefined. So, it is not renaming the function Commented Jul 7, 2015 at 15:36
  • I agree, maybe I should change the way I explained it, I'm not saying that func will exist, but what's the interest of writing it Commented Jul 7, 2015 at 15:37
  • I don't see any advantage of using this. As func is not defined, you cannot even use it. I'm also keen to know what this is Commented Jul 7, 2015 at 15:38

1 Answer 1

1

In your first example, you have a variable named myVar, which has a reference to a function named func. Your function isn't renamed.

In the secound example, though, you have the same variable myVar, but in this case, it's pointing to an anonymous function.

The reason for choosing number one over number two is that you get better output when errors occur, as it will print the function name. In the second example, it will simply say undefined if something goes wrong.

Edit: Found a more detailed answer here: Why use named function expressions?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.