Changes to JavaScript if

From Q
Jump to navigation Jump to search

Q provides the JavaScript language to allow users to write their own formula variables. The JavaScript language specification has changed subtly, and this change may affect a small number of Q users.

Who is Affected?

  • This affects formula variables written in JavaScript, where:
    • the last statement in a block is an 'if', and
    • that last statement has no else, and
    • the previous statement also ends with a value.
  • The change in behavior occurred with Q version 5.4.1. Q projects started using Q 5.4.1 or later already use the new behavior and are unaffected.
  • It does not affect formulas written in other languages: e.g. Excel-style formulas, R formulas.
  • It does not affect QScripts or Rules.

Example 1 of Affected Code

if (state == "CA") 1;
if (state == "OR") 2;
if (state == "WA") 3;

Old versions of Q would have calculated 1 for CA, 2 for OR and 3 for WA, otherwise NaN. It worked because old versions of JavaScript would look further up the script for a result, if the final statement omitted an 'else'. Now Q will calculate 3 for WA and NaN otherwise. This should be rewritten as:

if (state == "CA") 1;
else if (state == "OR") 2;
else if (state == "WA") 3;

Example 2 of Affected Code

if (state == "CA") 1;
if (state == "OR") 2;
if (state == "WA") 3;

This should be rewritten as:

var x = 0;
if (state == "CA") x = 1;
else if (state == "OR") x = 2;
else if (state == "WA") x = 3;

What to Do

Q will automatically detect most variables affected by this change, and they will show up in red on the Variables and Questions tab. Because Q now considers them to be in error you will need to edit and fix them before you can use them in tables or other outputs. E-mail support if you have trouble fixing your variables.