1

How do I access a variable inside a callback without reassigning it to a variable first?

For example, the following code works:

let volume = 0;
loudness.getVolume((err, vol) => {
    volume = vol;
});

But what if I wanted it to be assignable directly to a const. The following returns undefined:

const volume = loudness.getVolume((err, vol) => vol));
jfcali
  • 33
  • 6
  • I'm not super familiar with ecmascript but from a pure javascript perspective it looks like you're missing a return. Try ```const volume = loudness.getVolume((err, vol) => return vol));``` – TheCog19 Aug 29 '17 at 12:31
  • @TheCog this is correct es6 shorthand – Niles Tanner Aug 29 '17 at 12:31
  • You'd need to show `getVolume()`, but most likely the first example doesn't work (at least not always). If you log `volume` outside of the callback, it's still `0`. – baao Aug 29 '17 at 12:36
  • @TheCog in es6 u don't need a return statement – Bharathvaj Ganesan Aug 29 '17 at 12:37
  • 1
    I'm pretty sure your first snippet [does not work at all](https://stackoverflow.com/q/23667086/1048572). It's an asynchronous callback, right? – Bergi Aug 29 '17 at 12:39
  • @Bergi You are actually right. It is an async call and does not work outside the callback's scope. What I guess I meant was it works inside its scope but in the second snippet it does not. – jfcali Aug 29 '17 at 12:51
  • @jfcali But it's completely pointless. You cannot use the variable in that scope as you never when it's actually filled with a value. The point of callbacks is that you are supposed to put the code using the result inside the callback function - where it can directly access the `vol` parameter and does not need a `volume` variable. – Bergi Aug 29 '17 at 12:55
  • @Bergi Right. Got it. – jfcali Aug 29 '17 at 12:57

1 Answers1

2

The short answer is you can not. The callback function exists in it's own scope isolated from the rest of the code. The only way to extract that info to be used in the rest of the code is to assign it to a variable that exists in a parent scope.

In simple terms do what you did in your first example.

Niles Tanner
  • 3,911
  • 2
  • 17
  • 29
  • I could leave it at that, this was just out of curiosity. The thing is I recently came across an eslint configuration schema which prevents the use of `let` as well as reassigning variables. I guess this is only useful in Redux-like situations. – jfcali Aug 29 '17 at 12:46