Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Object-Oriented JavaScript (2015) Introduction to Methods Adding a Method to an Object

named functions stored in methods?

Hey andrew, I often see named functions used in methods. e.g.

var dice = {
  roll: function roll(){...}
}

You mention this isn't best practice, but is there any reason why this may be done?

2 Answers

Andrew Chalkley
STAFF
Andrew Chalkley
Treehouse Guest Teacher

I just said it's "unneeded" and you'll see them a lot as anonymous functions. However, having them as named functions can help certain debuggers see where the function is being called from.

For example, you could call it myDiceRollFunction like this:

var dice = {
  roll: function myDiceRollFunction(){...}
}

And console.log(dice.roll.name); and it'd print "myDiceRollFunction" however, the name attribute of a function, whilst widely implemented isn't a ECMA standard if I recall properly.

Michael Soileau
Michael Soileau
9,431 Points

Andrew, it's in EcmaScript 2015, so the newer standard support it officially. Here's an example to test out a difference.

test = {
  meTest: function meTest(){
    console.log(meTest);
// function meTest()
  }
}

If you do this, the console will print out function meTest. If you remove it:

test = {
  meTest: function (){
    console.log(meTest);
    // Error, meTest is not defined.
  }
}

You get error, since within the anonymous closure scope, meTest doesn't exist and so on up the chain unless you have another meTest hanging around. There's not a lot of practical reasons why you would want to refer to your own function like this.

test = {
  meTest: function meTest(){
    console.log(test.meTest);
    // function meTest()
  }
}

One good, practical reason would be a recursive function.