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

Devjyoti Ghosh
Devjyoti Ghosh
2,422 Points

Using ECMA 6

Why does the diceRoll function inside dice work when it isn't declared anywhere.

const dice = {
  roll: diceRoll= ()=> {
    let sides = 6;
    let randomNumber = Math.floor(Math.random() * sides) + 1;
    console.log(randomNumber);
    return "done";
  }
};

In ECMA 6 isn't arrow function syntax like this

const diceRoll = () => {};

edit: After tinkering with the code I am not sure why the same code doesn't work on jsfiddle but works in my treehouse workspace

edit: For other people having the same problem I would suggest giving this blog a read

1 Answer

Steven Parker
Steven Parker
231,275 Points

This line is an irregular definition:

  roll: diceRoll= ()=> {

It is not only defining "roll" as a method of "dice", but it is also performing an implicit global declaration of "diceRoll". Implicit globals are considered a bad practice, and are not allowed at all in "strict mode" where they cause an error. I don't have much experience with jsfiddle, but it may operate in strict mode by default.

Definiing "roll" without the implicit global would look like this:

  roll: () => {

While this works, it's probably worth mentioning that the MDN page on arrow functions gives this advice: "These function expressions are best suited for non-method functions"

Devjyoti Ghosh
Devjyoti Ghosh
2,422 Points

So is mixing of ES6 and ES5 fine if we are using normal anonymous method functions?

Steven Parker
Steven Parker
231,275 Points

I'm not sure what you mean by "mixing". ES6 extends ES5, adding new features but not removing any.

Arrow functions do not replace conventional functions, and as explained on the documentation page, they behave differently. There are several cases where you would not want to use an arrow function.

Devjyoti Ghosh
Devjyoti Ghosh
2,422 Points

Oh didn't know that. Thanks for taking the time and explaining the concepts.