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!

Jo Colina
  • 1,870
  • 7
  • 28
  • 46
  • If you run this, `func` is `undefined`. So, it is not renaming the `function` – Tushar Jul 07 '15 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 – Jo Colina Jul 07 '15 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 – Tushar Jul 07 '15 at 15:38

1 Answers1

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?

Christoffer Karlsson
  • 4,539
  • 3
  • 23
  • 36