0

I program with the spotify API.. the error are these 2 functions, I dont know how I call the 'setVolume' function in this arrow-function. Is this possible or is the Code wrong?

I don't know any further. Here is my code:

player.on('player_state_changed', state => {

   //... SOME CODE ...

   

   function setVolume(value) {
       player.setVolume(value).then(() => {
           console.log('Volume updated!');
       });
   }

});

(1) In the console I tried this:

setVolume(0.5)

(2) In the console I tried this:

player.on(setVolume(0.5))

~ and I got this error message: "player is not defined"

So how can I call the setVolume function from the console?

  • You can call **any** function in an arrow function? – Liam Jun 24 '20 at 14:07
  • 1
    settVolume is declared inside on that event, it is not going to be reachable outside that block. It does not make sense to be declared inside. What is the purpose for it to be inside? – epascarello Jun 24 '20 at 14:08
  • you would have to make all of this global, or edit the code in the inspector, all console code runs like ti was tacked onto the bottom of your code – Bagel03 Jun 24 '20 at 14:08
  • 1
    Does this answer your question? [How do JavaScript closures work?](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Liam Jun 24 '20 at 14:08
  • I dont know, Im new in stuff like Arrow functions – Dave Reiß Jun 24 '20 at 14:10
  • The arrow isn't the issue here. This is about variable scope and closures. Read the duplicate. An arrow function is just a [specialist function that encapsulates `this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). – Liam Jun 24 '20 at 14:11
  • @Liam I know this Website, so I tried this code "elements.map(({ length }) => length);" ~ and thought this works, but it isnt :) – Dave Reiß Jun 24 '20 at 14:18

1 Answers1

1

So how can I call the setVolume function from the console?

Fundamentally, you can't, not least because there isn't just one of them. There's a new setVolume function created every time the state change callback is run. Each of those functions is local to that state change callback and not accessible outside it. It would possible to have a global variable that you updated with the latest copy of the function each time one was created, but that's not likely to be a good idea. The function is presumably local for a reason.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875