Script and Value Assignment functions

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

FunctionDescriptionExample CallExample ResultVA
+adds termssum=3+25
subtracts termsdifference=3-21
*multiplies termsproduct=3*26
/divides termsquotient=3/21.5
%calculates the modulusmodulus=3%21
^exponentiates termssquare=3^29
sqrtcalculates the square rootresult=sqrt(9)3
abscalculates the absolute valueresult1=abs(-5)
result2=abs(5)
5
5
roundrounds number to decimalresult=round(2.35,1)2.4
VA -> functions supported in Value Assignment (VA) element. All functions are supported in Script element.

Statistics: standard

Download JSON of statistics reference survey and import it into your workspace.

FunctionDescriptionExample CallExample ResultVA
sumcalculates the sumsum(2,3,5)10
meancalculates the meanmean(2,3,5)3.3333…
mediancalculates the medianmedian(2,3,5)3
stdcalculates the standard deviationstd(2,3,5)1.5275…
variancecalculates the variancevariance(2,3,5)2.3333…
mincalculates the minimum valuesmin(2,3,5)2
maxcalculates the maximum valuemax(2,3,5)5
VA -> functions supported in Value Assignment (VA) element. All functions are supported in Script element.

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.

FunctionDescriptionExample CallExample ResultVA
meanValidcalculates the mean excluding NA and Missing answersmeanValid("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…
medianValidcalculates the median excluding NA and Missing answersmedianValid("q1,q2,q3,q4,q5")3
stdValidcalculates the standard deviation excluding NA and Missing answersstdValid("q1,q2,q3,q4,q5")1.5275…
varianceValidcalculates the variance excluding NA and Missing answersvarianceValid("q1,q2,q3,q4,q5")2.3333…
minValidcalculates the minimum values excluding NA and Missing answersminValid("q1,q2,q3,q4,q5")2
maxValidcalculates the maximum value excluding NA and Missing answersmaxValid("q1,q2,q3,q4,q5")5
VA -> functions supported in Value Assignment (VA) element. All functions are supported in Script element.

Randomisation

Download JSON of randomisation reference survey and import it into your workspace.

FunctionDescriptionExample CallSurvey ReferenceVA
randomreturns a real number between min (included) and max (excluded)random(min,max)
randBetweenreturns an intenger number between min (included) and max (included)randBetween(0,1)
randomIntreturns an integer number between min (included) and max (excluded)randomInt(min,max)Section 2 of randomisation survey
pickRandomreturns a randomly chosen element out of the given listpickRandom([var1,var2,var3])Section 1 of randomisation survey
shuffleshuffles the values of a matrixshuffle([var1,var2,var3])
shuffleChoicesWithinBlockrandomly sorts the answer options within specified blocksshuffleChoicesWithinBlock("q1",[1,2,3],[4],[5,6])
shuffleChoicesByBlockrandomly sorts the specified blocks of answer optionsshuffleChoicesByBlock("q1",[1,2,3],[4],[5,6])
VA -> functions supported in Value Assignment (VA) element. All functions are supported in Script element.

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)

ExampleDescriptionInputOutputVA
q1==1 ? var1=1 : nullif 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 nothingq1=1
q1=2
var1=1
var1=var1
q2>1 ? var2=1 : var2=0if 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 var2q2=1
q2=2
q2=3
var2=0
var2=1
var2=1
age>=18 and age<=65 ? counter=counter+1 : nullif question variable age has a value between 18 and 65, then add 1 to the custom variable counter or elsewise do nothingage=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" : nullif variable zip is between 1000 and 1007 or between 1010 and 1019, then assign “Lausanne” to variable town or elsewise do nothingzip=1008
zip=1018
zip=8005
town=town
town=”Lausanne”
town=town
equals(email1,email2)==true ? mailcheck=1 : mailcheck=0if both text entries from email1 and email2 are the same, then assign 1 to mailcheck or elsewise assign 0 to mailcheckemail1=”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=5nested 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=5age=5
age=25
age=45
age=65
age=85
group=1
group=2
group=3
group=4
group=5
VA -> functions supported in Value Assignment (VA) element. All functions are supported in Script element.

Texts

Download JSON of texts reference survey and import it into your workspace.

FunctionDescriptionExample CallExample ResultVA
concatconcatenates textsconcat("8005"," ","Zürich")“8005 Zürich”
equalscompares texts and returns either “true” or “false”equals("8005","Zürich")false
containscompares substring in texts and returns either “true” or “false”contains("or","World")true
countcounts the characters of a textcount("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”
indexOfreturns 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
subsetreplaces characters at defined positionsubset("8000 Zurich",index(4:7),"5 Zü")“8005 Zürich”
VA -> functions supported in Value Assignment (VA) element. All functions are supported in Script element.

Date & Time

Download JSON of data transformation reference survey and import it into your workspace.

FunctionDescriptionExample CallSurvey ReferenceVA
dateconverts a string (variable) to a date (variable)date("13/02/2024")
number2dateconverts a Unix timestamp to a datenumber2date(varTimestamp)
dateFormatformats a date (incl. time) as specified (data type string)dateFormat(varDate, "DD/MM/YYYY HH:mm:ss")
date2numberreturns the Unix timestamp (number of milliseconds) for a given datedate2number(varDate)Section 1 of data transformation survey
datetime2numberreturns the Unix timestamp (number of milliseconds) for a given time (incl. a date)datetime2number(varDateTime)
todayreturns current date and time in seconds (data type date)today()Section 1 of data transformation survey
nowreturns current date and time in seconds (data type date)
today()
now()
addDaysadds number of days specified to a given date (data type date)addDays(today(),-7)
getRunTimeInSecreturns the number of seconds since the beginning of the interviewgetRunTimeInSec()
VA -> functions supported in Value Assignment (VA) element. All functions are supported in Script element.

Data transformation

Download JSON of data transformation reference survey and import it into your workspace.

FunctionDescriptionExample CallSurvey ReferenceVA
parseNumberreturns integer number enclosed in textparseNumber(varText)Section 2 of data transformation survey
parseRealreturns real number enclosed in textparseReal(varText)
convertToStringconverts given number into textconvertToString(varNumber)Section 2 of data transformation survey
binreturns binary value of number (data type text)bin(varNumber)
hexreturns hexadecimal value of number (data type text)hex(varNumber)
toJSONconverts JSON string into JSON variabletoJSON(varText)
VA -> functions supported in Value Assignment (VA) element. All functions are supported in Script element.

Counters

Download JSON of counters reference survey and import it into your workspace.

FunctionDescriptionExample CallSurvey ReferenceVA
count_startedcalculates the number of interviews with status “InProgress”survey.count_startedSection 2a of randomisation survey
count_completedcalculates the number of interviews with status “Completed”survey.count_completedSection 2a of randomisation survey
countInterviewscalculates the number of interviews that meet the custom conditioncountInterviews(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
getCountlegacy function, use countInterviews instead
getCountQuestionreturns the number of questions in the whole surveygetCountQuestion()
getCountVariablereturns the number of variables in the whole surveygetCountVariable()
VA -> functions supported in Value Assignment (VA) element. All functions are supported in Script element.

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.

FunctionDescriptionExample CallExample ResultVA
csvToNumberArrayconverts a CSV string into a number array (data type matrix)csvToNumberArray('34,34,123,43')[34,34,123,43]
csvToStringArrayconverts 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
filterValidfilters only “valid” answers from the array, so excluding N/As, missings and nullsfilterValid(2,3,5,8888888,9999999)[2,3,5]
matrixToFlatArrayreturns a one dimensional matrix (=array) out of a multi dimensional matrixvarMatrix=[[1,2,3],[3,4,5],[5,6,7],[7,8,9]]
matrixToFlatArray(varMatrix[1:end,2])
[2,4,6,8]
arrayHasItemCheck if array contains object. Returns true or false.arrayHasItem([34, 34, 123, 43], 123)
mapmaps each value of a matrix according to a defined custom functionvarMatrix=[2,4,6,8]
custom function that replaces 2 or 6 with 0:
myFunction(value)= value==2 or value==6 ? 0 : value
mapping after the custom function:
map(varMatrix,myFunction)
[0,4,0,8]
sortsorts an arrayvarMatrix=[0,4,0,8]
sort(varMatrix,'asc')
[0,0,4,8]
filterfilters an array according to a defined custom functionvarMatrix=[0,0,4,8]
custom function that filters null missings and zero values:
myFunction(value)= value!=null and value!=0
filtering after the custom function:
filter(varMatrix,myFunction)
[4,8]
countdetermines the number of elements in an arrayvarMatrix=[4,8]
count(varMatrix)
2
meancalculates the mean of the elements of an arrayvarMatrix=[4,8]
mean(varMatrix)
6
resizeresizes (reduces or extends) a matrix or an arrayvarMatrix=[4,8]
varMatrix.resize([1])
varMatrix.resize([5])
varMatrix.resize([5],2)

[4]
[4,8,0,0,0]
[4,8,2,2,2]
matrixToHtmlgenerates HTML table code from a matrix variable; output via placeholder in the survey is a tablematrixToHtml(varMatrix)
or with formatted header
matrixToHtml(varMatrix,{firstRowAsHeader:true})
dataSourceToMatrixgets the results from a datasource within a report and writes the results into a matrix variabledataSourceToMatrix(reportID,
datasourceID)
VA -> functions supported in Value Assignment (VA) element. All functions are supported in Script element.

Survey element’s controls

Download JSON of controls reference survey and import it into your workspace.

FunctionDescriptionExample CallSurvey ReferenceVA
setSurveyFieldsReadOnlysets text fields or multiple choice checkboxes into read only modesetSurveyFieldsReadOnly([VariableName])
setSurveyFieldsEditablereverts the read only modesetSurveyFieldsEditable([VariableName])
setSectionOrdersets the display order of the next sectionssetSectionOrder(["Section C","Section A","Section B"])
hide (back button)hides the back buttonBackButton("hide")Section 2 of controls survey
hide (next button)hides the next button for a defined number of secondsNextButton("hide",5)Section 1 of controls survey
click (next button)automatically clicks the next button after a defined number of secondsNextButton("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 itNextButton("hideandclick",5)Section 1 of controls survey
VA -> functions supported in Value Assignment (VA) element. All functions are supported in Script element.

Special features

Download JSON of custom function and if-then-else reference survey and import it into your workspace.

FunctionDescriptionExample CallSurvey ReferenceVA
isNullOrUndefinedused in conditions to check if variable is null or undefinedisNullOrUndefined(varText)custom function and if-then-else reference survey
IsNotNullOrUndefinedused in conditions to check if variable is not null or undefined (not empty)IsNotNullOrUndefined(varText)custom function and if-then-else reference survey
list functionhides non-selected answers of a list in follow-up questionslist(choice) = answer(concat('brand_',choice.code)) == 1 ? true : false
setChoicesVisibility('bestbrand',list)
JSON of list function reference survey
getSurveyLinkgenerates a personal link for a certain surveylink=getSurveyLink(123)JSON of survey link reference survey
returnreturns the value of a certain variable as final result of the value assignmentreturn(var)
FunctionDescriptionExample CallExample Result
answerreturns raw data value of the variable. Normally, all N/As, Missings and nulls are treated as zerosanswer(q1)

where q1=N/A
9999999
answersreturns raw data value of the variables as array. Normally, all N/As, Missings and nulls are treated as zerosanswers(q1,q2,q3)

where q1=2, q2=3, q3=N/A
[2,3,9999999]
getChoiceTitlereturns 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”
getFromreturns the content of a JSON variable (up to 2 nested dimensions); pay attention to the enumerationvarJson = [
{"id":"1","name":"one"},
{"id":"2","name":"two"}
]


getFrom(varJson,'[1]')
getFrom(varJson,'[1].name')
getFrom(varJson[1],'name')






{“id”:”2″,”name”:”two”}
two
one
VA -> functions supported in Value Assignment (VA) element. All functions are supported in Script element.

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.

ExampleDescriptionInputOutputVA
myFunction(x) = x*x

myResult=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 myArraymyArray=[1,2,3]myResult=[1,4,9]
myFilter(x) = x!=null and x!=0

myResult=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 arraymyArray=[0,1,2,3,null]myResult=[1,2,3]
myFunction(x) = equals(q1,getFrom(x,'zip')) ? getFrom(x,'town') : null

myArray=matrixToFlatArray(ziptownlist)
myResult=map(myArray,myFunction)

nullFilter(x) = x!=null

myTown=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 nullFilterq1=”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+x

sum=0
foreach(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 loopsum=210
VA -> functions supported in Value Assignment (VA) element. All functions are supported in Script element.

Updated on August 26, 2026

Article Attachments

Was this article helpful?

Related Articles