Problems getting this to scope properly in arrow functions

Tell us what’s happening:

Two problems I am facing:
One:
My console.log throws an unexpected undefined after returning my describe method.
Two:
When I attempt to restructure my second method into an arrow function like the first,this becomes undefined. Why does it lose scope in this scenario?

Your code so far


function Dog(name) {
this.name = name;
}

Dog.prototype = {
// Only change code below this line
numLegs: 2,
eat: _ => console.log("nom nom nom"),
describe: function() {console.log(`My name is ${this.name}`)},
};
let hound = new Dog("Bonkers");
console.log(hound.describe());
// returns: 
My Name is Bonkers 
undefined

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.36.

Challenge: Change the Prototype to a New Object

Link to the challenge:

It’s because the function definition in your prototype has no return value. You are telling it to do a task console.log(My name is ${this.name} but the function is not returning anything to “describe”. Therefore the value of describe is undefined because your function returns undefined.

Try adding a return statement.

You have the same issue with the method “eat” too. Your function is not actually returning a value. There’s also a syntax error. Try reviewing the syntax for arrow functions.

On the first point, I just want to make sure it’s clear to you that your console.log is not throwing the undefined. The function is working just as you designed it. It is logging the message to the console. It’s then returning a value that is undefined because you don’t have a return statement returning anything.

On the second question, I’m pretty sure you can’t use => shorthand for closures. Th’at’s where you have an inner scoped function accessing a outer scoped (class) variable. The two ways I saw in the documentation that you are allowed to do it is

myfunction: function()

or

myfunction()

Here’s the documentation for the above: Method definitions - JavaScript | MDN

one thing about arrow function as I see a bit of confusion here
() => // something
is a correct implicit return

but, a console.log statement returns undefined. so if you put a console.log in a return statement (including implicit return) the function returns undefined

so, for your eat function, the function is returning undefined for that reason.

for the describe function you are directly missing a return statement (function syntax needs a return keyword for the function to return something. There isn’t, so it returns undefined by default.) but if you just add the return keyword, it will return the value from the console.log, which is still undefined

so if you want your methods to return something, you don’t want to return console.log statements