Accessibility of Javascripts codes in different part of the experiment

Dear all,

After some trial and error, I found that when we define a variable at the Begin Experiment tab of custom code, we cannot use that variable at different tabs, say Begin routine tab or End experiment tab. For example, the following codes give me an error:

// In the Begin Experiment Tab

var my_condition = Math.random();

// pick one condition randomly
if (my_condition > .5) {
    var condition = 'Condition1';
} else {
    var condition = 'Condition2';
    };

// In the End Experiment tab
psychoJS.experiment.addData('Condition', condition);

However, if I put all of the codes in the same tab, that will run nicely. Is that true? and, is there any way to use JS codes in different tabs? Because I need to define my condition randomly at the beginning of the experiment, and then use it as a text in the experiment in a routine (I do not want to change that text in every iteration of the routine).

Thank you.

Don’t specify
var condition = 'Condition1';
as that tells JS that the current code block is the entire scope of the variable callde condition.

If you just write
condition = 'Condition1';
then PsychoPy will automagically detect that you’ve added a variable and make it global on your behalf (by creating the var condition statement at the top of the script in a global scope).

1 Like

Thank you, Jon! It worked nicely :slight_smile: