Introduction
JavaScript is the scripting language of Q. It is used for:
- Creating numeric or text variables:
- from the Variables and Questions tab by right-clicking > Insert Variable(s) > JavaScript Formula > Numeric or Text.
- Creating Rules:
- from the Automate > Custom Rule or by selecting an existing rule > Edit > Edit JavaScript.
- Creating QScripts:
- from the toolbar via Automate > Run QScript (Macro) From File or Open QScript (Macro) Editor.
- Creating controls for R-based analysis tools:
- from the Properties tab in the object inspector via INPUTS JAVASCRIPT.
- Writing many of the functions available from the built-in menus.
JavaScript versus R
- Just like R variables, JavaScript variables are updated automatically in the project, and you can also easily go back to edit variables if you want to tweak the code.
- JavaScript code is run in the Q software and was originally designed as a scripting language for websites. R code, on the other hand, requires data to be packaged up and processed on our R servers and was specifically designed to do basic as well as advanced analysis.
- While usually there isn't a noticeable difference between creating a basic JavaScript variable and an R variable, if your data is quite large (think hundreds of thousands of cases) and you're doing a simple calculation, it may be faster to use JavaScript.
- Some advanced calculations may be easier - or only possible - to create using R.
- JavaScript can only reference the Name of a variable, whereas R can reference the Name or Label.
- JavaScript can only reference a single Variable at a time, whereas R can reference the Question.
- JavaScript is 0-based so the first iteration in a loop or array is 0, whereas in R it is 1.
- R objects, such as Calculations, control boxes, and other Standard R outputs cannot be referenced using JavaScript.
- When copying a variable over from a linked data set, it is often better to use JavaScript.
Q specific JavaScript functions
While all the standard functions are available in JavaScript, we have also created our own set of functions:
isNaN(variable_name)
- Returns a 0 if the variable is not missing and a 1 if the variable is missing.Q.AsNumeric(variable_name)
- Converts a Text Variable containing numbers into a Numeric Variable.Q.Label(variable_name)
- Converts a variable's value into its corresponding label. e.g. for a Gender question, 2 would become Female.Q.Source(variable_name)
- Returns the original source value of a variable, ignoring any recoding or Missing Data settings.
Next
How to Work with Conditional JavaScript Formulas
How to Manipulate Strings Using JavaScript
How to Work with JavaScript Arrays and Loops
See Also
How to Troubleshoot JavaScript Code in Q