Getting undefined even when function works well

Hello everyone,

My question is not specific to one excercie, I got this in many, but I saw it on this one :
JS Privacy Exercise

I often get an undefined message in the console, it appears after what I wanted to log on the console using a function, here is an exemple with the code and the result :

Here is the code used :

const robot = { _energyLevel: 100, recharge(){ this._energyLevel += 30; console.log(`Recharged! Energy is currently at ${this._energyLevel}%.`) } }; console.log(robot.recharge())

Do you guys know why I get this undefined with no reason ?

Thank you for your help

Hello,
console.log(robot.recharge())
The above line of code is basically saying, print to the screen the return value of calling the robot.recharge method. But, as it doesn’t have one, that’s what the undefined is.

You could either call it without the console.log;
i.e. just have
robot.recharge();
on line 15.

or keep 15 as it is but on line 9 return the string instead of using console log there;
i.e.
return ‘Recharged! Energy is currently at ${this._energyLevel}%.’;

Hope that helps.

Edit ( just to avoid confusion the line numbers are referring to the codebyte, not your original image )

1 Like

If I understand well, what I do is like writing :
console.log(console.log(robot.recharge()))

I am right ?

not quite, but sort of. I think I can see where you’re coming from.

Console.log will only print something if it has some sort of value/string to print.
When you use it to call a function, then the function needs to have a return value, or you’ll get ‘undefined’.