Wakefield's Daily Tips

ReferenceError: varName is not defined

This is one of the most common errors in online experiments

It is also one of the easiest to solve. The issue is one of “scope”. To define a variable so it has scope across your whole experiment, all you have to do is assign it a value. Don’t edit your JavaScript to add “var” or “let” commands. To give your variable scope assign the value in a Begin Experiment code component tab outside any clauses (i.e. no Python indents).

I usually start my experiments with a routine called setup (or start) containing a code component called code_setup which contains all of the Begin Experiment code including default values for any variables which first get used in a clause.

The one exception to this is any variable defined within a spreadsheet. Online these variables can be used, but should not be modified. You will get this error if you try to use a spreadsheet variable before it is available, for example by setting a parameter value to constant instead of set every repeat or have manually defined JavaScript variables using let and try to use them elsewhere. If you want to sometimes edit the value from the spreadsheet, use a second variable.

For example I could have:

if TargetImage == 'x':
    thisImage = 'transparent.png'
else:
    thisImage = TargetImage  

Since the above code would fail unless I defined thisImage in Begin Experiment, I actually tend to use code that looks more like this:

thisImage = TargetImage
if TargetImage = 'x':
    thisImage = 'transparent.png'