3

I always used to write functions like this:

var myFunction = function(param) {
    console.log(param);
};
myFunction('myFunction');

Now I've seen this:

var otherFunction = function whyNameHere(param) {
    console.log(param);
};
otherFunction('otherFunction');

and I'm wondering what is whyNameHere? When and why should functions be written like this? Also I can call it exactly the same as the myFunction function above.. why should someone write whyNameHere? Also is there a naming for this kind of function?

If anyone wants to play with it, here is a fiddle

caramba
  • 21,963
  • 19
  • 86
  • 127

1 Answers1

0

Using that allows you to set the .name property on the created function object.

> var f = function g() { }
< undefined
> f.name
< "g"

It's impossible to change it later:

> f.name = "f"
< "f"
> f.name
< "g"

And it's useful for... things.


Example:

setImmediate(function unicorns() {
    console.log("rainbow");
    throw "glitter";
});

Will present itself on the stack trace as:

Uncaught glitter
    unicorns @ VM691:4

Instead of

Uncaught glitter
    (anonymous function) @ VM693:4
Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135
  • [Function.name](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Function/name) This is a new technology, part of the ECMAScript 2015 (ES6) standard. So available not in all browser – Grundy Oct 19 '15 at 11:22
  • @Grundy maybe it's just me, but for me ES7 is new technology. ES6 has been here for a while, really. Sure, not fully locked and standarized, but you get the point. – Bartek Banachewicz Oct 19 '15 at 11:22
  • seems to full support ES6 a lot of time – Grundy Oct 19 '15 at 11:23
  • hmm, well now from what I understood the answers (which my question should be the duplicate of) I could/can use g() only inside f !? so if that is true that would of actually have been the answer on my question (as part one) the seccond part was if that has a name ... – caramba Oct 19 '15 at 11:23
  • 1
    @caramba The `g` name doesn't leak outside the assignment, if that's what you're asking about. – Bartek Banachewicz Oct 19 '15 at 11:24
  • well yes thats kind of what I was asking. I didn't see any reason of how and where to use it.. – caramba Oct 19 '15 at 11:25
  • If you can explain `And it's useful for... things.` with a working example of sense I'll like your answer. I like the joke a lot but it really doesn't helps.. – caramba Oct 19 '15 at 11:30
  • @caramba sure. There you go. – Bartek Banachewicz Oct 19 '15 at 11:36