Writing ‘Real’ Code

From Q
Jump to navigation Jump to search

It is possible to write ‘real code’ in the Expression box. For example:

var TotalSpend = 0; //initializing variable
if (!isNaN(Q30_A_2)) TotalSpend = TotalSpend + Q30_A_2;
if (!isNaN(Q30_B_2)) TotalSpend = TotalSpend + Q30_B_2;
if (!isNaN(Q30_C_2)) TotalSpend = TotalSpend + Q30_C_2;
if (!isNaN(Q30_D_2)) TotalSpend = TotalSpend + Q30_D_2;

In this example:

  • We are able to make comments in the code (i.e., //initializing variable).
  • We have declared a variable within the Expression box called TotalSpend. Note: the use of variable in this sense is the standard use within computer programming (i.e., it is not the same as elsewhere within Q, where a variable refers to a column of data in the Data tab).
  • We have distinct lines in the code, which are computed in the order they are written, each performing an operation (i.e., adding to the TotalSpend variable if the condition in the if statement is true.
  • A semicolon is being used to indicate a new line. So, the fifth line actually contains two distinct lines of code.
  • The = sign is assigning a value to TotalSpend (i.e., it is different to ==).
  • The ! operator indicates ‘not’. That is, !isNaN(Q30_A_2) means that ‘Q30_A_2 is not missing’.

Creating variables in the Expression

Variables created within the code are only used in intermediate calculations and are automatically deleted after the code has run (i.e., they do not appear in the Variables and Questions tab.)

For example, consider a numeric variable with the expression 12 + 19. This can equivalently be written as:

var a = 12
var b = 19;
a + b;

Note that the last line of code is the expression which is evaluated to produce the result used within Q.

Alternatively, we can equivalently write:

var a = 12;
var b = 19;
var c;
c = a + b;


var a = 12;
var b = 19;
var c = a + b;

However, the following would not work as you might expect, as the final line is an instruction to compute a variable, rather than a result:

var a = 12;
var b = 19;
var c = a + b;

Were you to actually have the above three lines of code, the result would be a variable where each observation has the value NaN, which is the default when there is no specific result being returned by the code.

In this example nothing is to be gained by introducing such complexity. However, there are two key benefits to creating variables within code:

  • It can make the code easier to read.
  • It can make it easier to re-use the code at a later stage.

See also