Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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.