This page lists all functions possible to use in Script and Value Assignment survey elements.
If you are not yet familiar with basic concepts of survey programming in Survalyzer, we recommend to first read the following pages:
Disclaimer: Limited Support. If you have an Expert user license, you can use all functions described in this page. However, if you are stuck, you need an extended support contract (SLA) to get our assistance. Survalyzer standard product support does not include Scripts. Contact our sales team to get a extended support contract.
Disclaimer: Survalyzer New Design vs Old Design. During transition period, it is possible to use either old or new survalyzer design. Documentation below describes the “new design” state. Script vs Value Assignment differentiation is only present in the new design. In the old design version Value Assignment = Script.
All functions below are supported in “Script” survey element.
Only selected functions are supported in “Value Assignment” (VA) survey element. Please check “VA” column in tables below for reference.
Math.js functions
As a foundation of the Script element we use math.js. There are out-of-the-box functions you can use. In case, the following listed functions do not fulfill your requirements, you may search for more in math.js function reference: https://mathjs.org/docs/reference/functions.html
All Math.js functions are supported in Script element. To check Value Assignment (VA) functions support, please reference tables below.
Arithmetic
| Function | Description | Example Call | Example Result | VA |
| + | adds terms | sum=3+2 | 5 | ✅ |
| – | subtracts terms | difference=3-2 | 1 | ✅ |
| * | multiplies terms | product=3*2 | 6 | ✅ |
| / | divides terms | quotient=3/2 | 1.5 | ✅ |
| % | calculates the modulus | modulus=3%2 | 1 | ✅ |
| ^ | exponentiates terms | square=3^2 | 9 | ✅ |
| sqrt | calculates the square root | result=sqrt(9) | 3 | ✅ |
| abs | calculates the absolute value | result1=abs(-5)result2=abs(5) | 5 5 | ✅ |
| round | rounds number to decimal | result=round(2.35,1) | 2.4 | ✅ |
Statistics: standard
Download JSON of statistics reference survey and import it into your workspace.
| Function | Description | Example Call | Example Result | VA |
| sum | calculates the sum | sum(2,3,5) | 10 | ✅ |
| mean | calculates the mean | mean(2,3,5) | 3.3333… | ✅ |
| median | calculates the median | median(2,3,5) | 3 | ✅ |
| std | calculates the standard deviation | std(2,3,5) | 1.5275… | ✅ |
| variance | calculates the variance | variance(2,3,5) | 2.3333… | ✅ |
| min | calculates the minimum values | min(2,3,5) | 2 | ✅ |
| max | calculates the maximum value | max(2,3,5) | 5 | ✅ |
Statistics: excluding N/As and Missings
Standard statistics functions work well in simple scenarios, however they treat N/A and Missing answers as 0 (zero) in calculations. To exclude N/A and Missings answers from calculations, use the following “Valid” function versions:
Quotation marks must be used in those functions brackets to work correctly (see examples below). Without quotation marks they will work as normal functions and will NOT exclude N/A and Missing answers.
| Function | Description | Example Call | Example Result | VA |
| meanValid | calculates the mean excluding NA and Missing answers | meanValid("q1,q2,q3,q4,q5")where for all functions in this table: q1=2, q2=3, q3=5, q4=N/A, q5=null | 3.3333… | ✅ |
| medianValid | calculates the median excluding NA and Missing answers | medianValid("q1,q2,q3,q4,q5") | 3 | ✅ |
| stdValid | calculates the standard deviation excluding NA and Missing answers | stdValid("q1,q2,q3,q4,q5") | 1.5275… | ✅ |
| varianceValid | calculates the variance excluding NA and Missing answers | varianceValid("q1,q2,q3,q4,q5") | 2.3333… | ✅ |
| minValid | calculates the minimum values excluding NA and Missing answers | minValid("q1,q2,q3,q4,q5") | 2 | ✅ |
| maxValid | calculates the maximum value excluding NA and Missing answers | maxValid("q1,q2,q3,q4,q5") | 5 | ✅ |
Randomisation
Download JSON of randomisation reference survey and import it into your workspace.
| Function | Description | Example Call | Survey Reference | VA |
| random | returns a real number between min (included) and max (excluded) | random(min,max) | ✅ | |
| randBetween | returns an intenger number between min (included) and max (included) | randBetween(0,1) | ✅ | |
| randomInt | returns an integer number between min (included) and max (excluded) | randomInt(min,max) | Section 2 of randomisation survey | ✅ |
| pickRandom | returns a randomly chosen element out of the given list | pickRandom([var1,var2,var3]) | Section 1 of randomisation survey | ➖ |
| shuffle | shuffles the values of a matrix | shuffle([var1,var2,var3]) | ➖ | |
| shuffleChoicesWithinBlock | randomly sorts the answer options within specified blocks | shuffleChoicesWithinBlock("q1",[1,2,3],[4],[5,6]) | ➖ | |
| shuffleChoicesByBlock | randomly sorts the specified blocks of answer options | shuffleChoicesByBlock("q1",[1,2,3],[4],[5,6]) | ➖ |
Conditional instructions (if-then-else)
The basic syntax of a conditional instruction is:
IF condition ? THEN action : ELSE action
– the question mark and the colon are required
– only one THEN action and one ELSE action can be defined
– in case of no action use the word null
– the condition can contain logical operators and and or as well as brackets
– two or more conditional instructions can be nested (corresponds to ELSEIF)
| Example | Description | Input | Output | VA |
q1==1 ? var1=1 : null | if question variable q1 has the value 1 (e.g. first answer of single response question is chosen), then assign the value 1 to the custom variable var1 or elsewise do nothing | q1=1 q1=2 | var1=1 var1=var1 | ➖ |
q2>1 ? var2=1 : var2=0 | if question variable q2 has a value bigger than 1, then assign the value 1 to custom variable var2 or elsewise assign the value 0 to custom variable var2 | q2=1 q2=2 q2=3 | var2=0 var2=1 var2=1 | ➖ |
age>=18 and age<=65 ? counter=counter+1 : null | if question variable age has a value between 18 and 65, then add 1 to the custom variable counter or elsewise do nothing | age=15 age=45 age=75 | counter=counter counter=counter+1 counter=counter | ➖ |
(zip>=1000 and zip<=1007) or (zip>=1010 and zip<=1019) ? town="Lausanne" : null | if variable zip is between 1000 and 1007 or between 1010 and 1019, then assign “Lausanne” to variable town or elsewise do nothing | zip=1008 zip=1018 zip=8005 | town=town town=”Lausanne” town=town | ➖ |
equals(email1,email2)==true ? mailcheck=1 : mailcheck=0 | if both text entries from email1 and email2 are the same, then assign 1 to mailcheck or elsewise assign 0 to mailcheck | email1=”a@bc.de” email2=”a@bc.de” email1=”a@bc.de” email2=”k@lm.no” | mailcheck=1 mailcheck=0 | ➖ |
age<18 ? group=1 : age<30 ? group=2 : age<50 ? group=3 : age<=65 ? group=4 : group=5 | nested conditional instructions: if age<18 then group=1 elseif age<30 then group=2 elseif age<50 then group=3 elseif age<=65 then group=4 elsewise group=5 | age=5 age=25 age=45 age=65 age=85 | group=1 group=2 group=3 group=4 group=5 | ➖ |
Texts
Download JSON of texts reference survey and import it into your workspace.
| Function | Description | Example Call | Example Result | VA |
| concat | concatenates texts | concat("8005"," ","Zürich") | “8005 Zürich” | ✅ |
| equals | compares texts and returns either “true” or “false” | equals("8005","Zürich") | false | ➖ |
| contains | compares substring in texts and returns either “true” or “false” | contains("or","World") | true | ➖ |
| count | counts the characters of a text | count("8005 Zürich") | 11 | ✅ |
| [start:stop] | returns a substring, beginning at “start” and ending at “stop” (number of character) | "8005 Zürich"[1:4] | “8005” | ➖ |
| indexOf | returns the start position of a search string (be aware: first character is 0) | indexOf("8005 Zürich","Zürich")indexOf("8005 Zürich","Utrecht") | 5 -1 | ➖ |
| subset | replaces characters at defined position | subset("8000 Zurich",index(4:7),"5 Zü") | “8005 Zürich” | ➖ |
Date & Time
Download JSON of data transformation reference survey and import it into your workspace.
| Function | Description | Example Call | Survey Reference | VA |
| date | converts a string (variable) to a date (variable) | date("13/02/2024") | ✅ | |
| number2date | converts a Unix timestamp to a date | number2date(varTimestamp) | ➖ | |
| dateFormat | formats a date (incl. time) as specified (data type string) | dateFormat(varDate, "DD/MM/YYYY HH:mm:ss") | ✅ | |
| date2number | returns the Unix timestamp (number of milliseconds) for a given date | date2number(varDate) | Section 1 of data transformation survey | ➖ |
| datetime2number | returns the Unix timestamp (number of milliseconds) for a given time (incl. a date) | datetime2number(varDateTime) | ➖ | |
| today | returns current date and time in seconds (data type date) | today() | Section 1 of data transformation survey | ✅ |
| now | returns current date and time in seconds (data type date)today() | now() | ✅ | |
| addDays | adds number of days specified to a given date (data type date) | addDays(today(),-7) | ✅ | |
| getRunTimeInSec | returns the number of seconds since the beginning of the interview | getRunTimeInSec() | ✅ |
Data transformation
Download JSON of data transformation reference survey and import it into your workspace.
| Function | Description | Example Call | Survey Reference | VA |
| parseNumber | returns integer number enclosed in text | parseNumber(varText) | Section 2 of data transformation survey | ✅ |
| parseReal | returns real number enclosed in text | parseReal(varText) | ✅ | |
| convertToString | converts given number into text | convertToString(varNumber) | Section 2 of data transformation survey | ➖ |
| bin | returns binary value of number (data type text) | bin(varNumber) | ➖ | |
| hex | returns hexadecimal value of number (data type text) | hex(varNumber) | ➖ | |
| toJSON | converts JSON string into JSON variable | toJSON(varText) | ➖ |
Counters
Download JSON of counters reference survey and import it into your workspace.
| Function | Description | Example Call | Survey Reference | VA |
| count_started | calculates the number of interviews with status “InProgress” | survey.count_started | Section 2a of randomisation survey | ✅ |
| count_completed | calculates the number of interviews with status “Completed” | survey.count_completed | Section 2a of randomisation survey | ✅ |
| countInterviews | calculates the number of interviews that meet the custom condition | countInterviews(customCondition)example for a customCondition: countInterviews(q1==1 and survey.State=='Completed')warning: variables cannot be used on the right-hand side of the conditions, only constants. | Section 1 of counters survey | ➖ |
| getCount | legacy function, use countInterviews instead | – | ➖ | |
| getCountQuestion | returns the number of questions in the whole survey | getCountQuestion() | ➖ | |
| getCountVariable | returns the number of variables in the whole survey | getCountVariable() | ➖ |
Important: If a Data Cube is enabled for the survey, counter functions such as countInterviews(), count_started and count_completed use the data currently synchronized to the Data Cube. They therefore do not represent live interview counts between cube refreshes and should not be used for logic that depends on real-time counts.
Array & Matrix
Download JSON of matrixto reference survey and import it into your workspace.
| Function | Description | Example Call | Example Result | VA |
| csvToNumberArray | converts a CSV string into a number array (data type matrix) | csvToNumberArray('34,34,123,43') | [34,34,123,43] | ➖ |
| csvToStringArray | converts a CSV string into a string array (data type matrix) | csvToStringArray('34, 34, 123 , 43') | [“34″,”34″,”123″,”43”] | ➖ |
| [dim1,dim2] | returns the element of a matrix at position “dim1” and “dim2” | varMatrix=[[1,2,3],[3,4,5],[5,6,7],[7,8,9]]varMatrix[2,3] | 5 | ➖ |
| filterValid | filters only “valid” answers from the array, so excluding N/As, missings and nulls | filterValid(2,3,5,8888888,9999999) | [2,3,5] | ➖ |
| matrixToFlatArray | returns a one dimensional matrix (=array) out of a multi dimensional matrix | varMatrix=[[1,2,3],[3,4,5],[5,6,7],[7,8,9]]matrixToFlatArray(varMatrix[1:end,2]) | [2,4,6,8] | ➖ |
| arrayHasItem | Check if array contains object. Returns true or false. | arrayHasItem([34, 34, 123, 43], 123) | ➖ | |
| map | maps each value of a matrix according to a defined custom function | varMatrix=[2,4,6,8] custom function that replaces 2 or 6 with 0: myFunction(value)= value==2 or value==6 ? 0 : valuemapping after the custom function: map(varMatrix,myFunction) | [0,4,0,8] | ➖ |
| sort | sorts an array | varMatrix=[0,4,0,8]sort(varMatrix,'asc') | [0,0,4,8] | ➖ |
| filter | filters an array according to a defined custom function | varMatrix=[0,0,4,8] custom function that filters null missings and zero values: myFunction(value)= value!=null and value!=0filtering after the custom function: filter(varMatrix,myFunction) | [4,8] | ➖ |
| count | determines the number of elements in an array | varMatrix=[4,8]count(varMatrix) | 2 | ➖ |
| mean | calculates the mean of the elements of an array | varMatrix=[4,8]mean(varMatrix) | 6 | ➖ |
| resize | resizes (reduces or extends) a matrix or an array | varMatrix=[4,8]varMatrix.resize([1])varMatrix.resize([5])varMatrix.resize([5],2) | [4] [4,8,0,0,0] [4,8,2,2,2] | ➖ |
| matrixToHtml | generates HTML table code from a matrix variable; output via placeholder in the survey is a table | matrixToHtml(varMatrix)or with formatted header matrixToHtml(varMatrix,{firstRowAsHeader:true}) | ➖ | |
| dataSourceToMatrix | gets the results from a datasource within a report and writes the results into a matrix variable | dataSourceToMatrix(reportID,datasourceID) | ➖ |
Survey element’s controls
Download JSON of controls reference survey and import it into your workspace.
| Function | Description | Example Call | Survey Reference | VA |
| setSurveyFieldsReadOnly | sets text fields or multiple choice checkboxes into read only mode | setSurveyFieldsReadOnly([VariableName]) | ➖ | |
| setSurveyFieldsEditable | reverts the read only mode | setSurveyFieldsEditable([VariableName]) | ➖ | |
| setSectionOrder | sets the display order of the next sections | setSectionOrder(["Section C","Section A","Section B"]) | ➖ | |
| hide (back button) | hides the back button | BackButton("hide") | Section 2 of controls survey | ➖ |
| hide (next button) | hides the next button for a defined number of seconds | NextButton("hide",5) | Section 1 of controls survey | ➖ |
| click (next button) | automatically clicks the next button after a defined number of seconds | NextButton("click",5) | Section 1 of controls survey | ➖ |
| hideandclick (next button) | hides the next button for a defined number of seconds and then automatically clicks on it | NextButton("hideandclick",5) | Section 1 of controls survey | ➖ |
Special features
Download JSON of custom function and if-then-else reference survey and import it into your workspace.
| Function | Description | Example Call | Survey Reference | VA |
| isNullOrUndefined | used in conditions to check if variable is null or undefined | isNullOrUndefined(varText) | custom function and if-then-else reference survey | ➖ |
| IsNotNullOrUndefined | used in conditions to check if variable is not null or undefined (not empty) | IsNotNullOrUndefined(varText) | custom function and if-then-else reference survey | ➖ |
| list function | hides non-selected answers of a list in follow-up questions | list(choice) = answer(concat('brand_',choice.code)) == 1 ? true : falsesetChoicesVisibility('bestbrand',list) | JSON of list function reference survey | ➖ |
| getSurveyLink | generates a personal link for a certain survey | link=getSurveyLink(123) | JSON of survey link reference survey | ✅ |
| return | returns the value of a certain variable as final result of the value assignment | return(var) | ➖ | |
| Function | Description | Example Call | Example Result | |
| answer | returns raw data value of the variable. Normally, all N/As, Missings and nulls are treated as zeros | answer(q1) where q1=N/A | 9999999 | ✅ |
| answers | returns raw data value of the variables as array. Normally, all N/As, Missings and nulls are treated as zeros | answers(q1,q2,q3) where q1=2, q2=3, q3=N/A | [2,3,9999999] | ➖ |
| getChoiceTitle | returns question choice label (e.g. Multiple Response question or Single Response question) | Choices labels with HTML:getChoiceTitle('q1', 1)}}getChoiceTitle(q1_1)}}Choices labels without HTML, 2 options: getChoiceTitle('q1', 1, true)}}getChoiceTitle(q1_1, true)}} | “<b>Choice 1</b>” “Choice 1” | ✅ |
| getFrom | returns the content of a JSON variable (up to 2 nested dimensions); pay attention to the enumeration | varJson = [getFrom(varJson,'[1]') | {“id”:”2″,”name”:”two”} two one | ➖ |
Mapping, filtering and foreach loops with custom functions
Math.js features a function called map that creates a new array or matrix out of a given array or matrix based on a callback function. You can use this as a foreach loop as described below.
Read more about the map function on math.js documentation.
You may define any callback function you want – therefore, let us call them custom functions. Make sure the custom function is defined before you do the map function call.
Besides the map function also a filter function exists that basically uses the same logic. In contrast to the mapping the filtering keeps certain elements according to the custom function and removes the others.
Instead, if you want to use a loop that does not necessarily change the matrix or array used for the looping, you can work with the foreach function. You still need a matrix or an array to loop through all the elements, but you may create an auxiliary array with e.g. enumerated values first.
| Example | Description | Input | Output | VA |
myFunction(x) = x*xmyResult=map(myArray,myFunction) | the custom function myFunction squares each provided value; the map function hands over myArray to myFunction for creating the new array myResult with the squares for each element of myArray | myArray=[1,2,3] | myResult=[1,4,9] | ➖ |
myFilter(x) = x!=null and x!=0myResult=filter(myArray,myFilter) | the custom function myFilter checks for each provided value if it is not null and not 0; the filter function hands over myArray to myFilter for filtering out empty and 0 values and keeping all other values in the new myResult array | myArray=[0,1,2,3,null] | myResult=[1,2,3] | ➖ |
myFunction(x) = equals(q1,getFrom(x,'zip')) ? getFrom(x,'town') : nullmyArray=matrixToFlatArray(ziptownlist)myResult=map(myArray,myFunction)nullFilter(x) = x!=nullmyTown=filter(myResult,nullFilter)[1] | myFunction is a lookup function that loops through the ziptownlist (JSON converted to flat array) and compares all list values with the answer from q1; myResult keeps the matching value and myTown returns the only left element after using the nullFilter | q1=”8000″ ziptownlist=[ {“zip”:”1000″, “town”:”Lausanne”}, {“zip”:”1200″, “town”:”Genève”}, {“zip”:”3000″, “town”:”Bern”}, {“zip”:”4000″, “town”:”Basel”}, {“zip”:”8000″, “town”:”Zürich”}] | myResult=[null,null,null,null,”Zürich”] myTown=”Zürich” | ➖ |
auxiliaryArray=range(1,20)myFunction(x) = sum=sum+xsum=0foreach(auxiliaryArray,myFunction) | auxiliaryArray is created to have 20 elements from 1 to 20; myFunction sums-up the numbers 1 to 20 by using a foreach loop | sum=210 | ➖ |