How to use 'this'?

I want to have this function as an arrow one (cuz it looks cool) and it works fine for small numbers but problem accours at large numbers where exponent is used, so i tried to solve it like that but this isn’t defined, what to do?

Your code so far


const powerDigitSum = exp => String(Math.pow(2, exp))
.split('').slice(0, this.indexOf('e')).reduce((sum, n) => sum + Number(n), 0);

console.log(Math.pow(2, 128))

Your browser information:

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

Challenge: Problem 16: Power digit sum

Link to the challenge:

Well, there are many reason to choose arrow functions over the function declaration, one of which is that arrow function:

Does not have its own bindings to this or super , and should not be used as methods .

You can read the documentation about them here.

Hope it helps :slight_smile:

there’s a lot of material and I don’t uderstand what to switch this with, I already read some parts before posting this post, I wouldn’t post it if I’d understand

Well, long story short: you can’t, or at least not in any reasonable way.
Arrow function are specifically designed to not bind this, therefore making it “impossible” to use it to chain methods.

For a case like this one, where you want to heavily rely on chaining the good 'ol function is the right tool for the job.

(also personal opinion, even nicer to read than the proposed arrow :wink: )

1 Like