0

I'm trying to assign a value to a global variable, but am encountering a scope problem. For example, I extract the value resp[Q0] within a function and need to assign this to the variable PID which is outside the function.

I'm doing this, because I then need to store this value in a dictionary (additionalInfo) with other variables. Below is my stripped down code, but my script is significantly longer, so it does need to occur in this odd organization.

You'll see that within the function PID is properly assigned a value. Outside the function, it doesn't. (See my console.logs) So currently I'm receiving an error that PID is undefined.

    var PID;

    var collectPID = {
      timeline: [text],
      loop_function: function(data) {
        resp = JSON.parse(data.values()[0]['responses']);
        PID = resp['Q0'];
        console.log('this works', PID);
      }
    };

    console.log('this doesnt work', PID);

    var additionalInfo = {
      SONA: PID,
      other: info,
      on_finish: main_on_finish
    }
psychcoder
  • 543
  • 3
  • 14
  • When does your loop_function fire? – Muzaffer Galata Oct 08 '20 at 07:21
  • In lines 3-10, you ***define*** an object, including a function. But you never execute the function. Immediately afterwards in line 12, you print the value of `PID`, which has never been altered between having been defined and when you try to print it. – deceze Oct 08 '20 at 07:21

0 Answers0