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 Understanding this

Yanfei Yu
Yanfei Yu
4,259 Points

Using arrow function leads to undefined result?

Hi there,

I am trying to use arrow function in the roll method, like: roll: () => {...this.sides....} However the result of using this in side the arrow function when calling dice.roll() is undefined. If I instead just use dice.sides in the random number generation process, everything is fine.

What is the reason for that? Can anyone help me understand this? Thanks so much!

Hei Yanfei, it would be helpful if you could post your code :).

Yanfei Yu
Yanfei Yu
4,259 Points

here is the code:

var dice = {
  sides: 6,
  roll:  ()=> {
    var randomNumber = Math.floor(Math.random() * this.sides) + 1;
    console.log(randomNumber);
  }
}

var dice10 = {
  sides: 10,
  roll:  ()=> {
    var randomNumber = Math.floor(Math.random() * this.sides) + 1;
    console.log(randomNumber);
  }
}

also when I change the arrow function to just function(){}, everything works well too

roll: function () {
    var randomNumber = Math.floor(Math.random() * this.sides) + 1;
    console.log(randomNumber);
}

1 Answer

Hei Yanfei, one way for you to do it would be like this:

var dice = {
  sides: 6,
  roll(){
    var randomNumber = Math.floor(Math.random() * this.sides) + 1;
    console.log(randomNumber);
  }
}


dice.roll()

Also I found this article, which explains it perfectly: https://dmitripavlutin.com/when-not-to-use-arrow-functions-in-javascript/.

Hope that helps you out :).

Yanfei Yu
Yanfei Yu
4,259 Points

Thanks a lot, Tobias! That article does clarify many concepts!