JavaScript functions

Medallia Experience Cloud supports most of the common JavaScript functions that are available in any JavaScript environment. Below are some of the supported functions.

These are useful in fields (K-fields and R-fields), Auto Importer Preprocessors, and Custom modules (AA2). Type Control + Space in the JavaScript editor to see the suggested functions.

JavaScript functions for K-fields

Numbers and string functions

FunctionDescription
avg(number1, number2 ...)Returns the average of the given numbers. For example, this returns 2:
avg(1, 2, 3)
random()Return a random double between 0.00 and 1.00, based on the implicit surveyId.
sum(number1, number2 ...)Return sum of the given Integers.
trim(String)Return the given string with leading and trailing whitespace removed. For example, this returns \"hello world\":
var s = \" hello world \";
trim(s)

Date and time functions

FunctionDescription
daysDifferenceBy24Hours(date1, date2)Returns the number of days between the two dates, counting 24 hours as one day (rounded down). For example, this returns 1:
var d1 = new Date(2013, 3, 2, 11, 30, 0);
var d2 = new Date(2013, 3, 3, 12, 24, 0);
daysDifferenceBy24Hours(d1, d2)
daysDifferenceByMidnights(date1, date2)Return the number of days between the two dates, counting each midnight as a new day. For example, this returns 2:
var d1 = new Date(2013, 3, 1, 11, 30, 0);
var d2 = new Date(2013, 3, 3, 4, 0, 0);\
daysDifferenceByMidnights(d1, d2
hoursDifference(date1, date2)Return the number of hours between the two dates. For example, this returns 2:
var d1 = new Date(2013, 3, 1, 10, 30, 0);
var d2 = new Date(2013, 3, 1, 12, 30, 0);
hoursDifference(d1, d2
millisDifference(date1, date2)Return the number of milliseconds between the two dates. For example, this returns 2000:
var d1 = new Date(2013, 3, 1, 11, 30, 0);
var d2 = new Date(2013, 3, 1, 11, 30, 2);
millisDifference(d1, d2
between(number1, number2, number3)Returns TRUE if the first parameter is in the inclusive range formed between the second and third parameters. For example,this returns TRUE:
between(3, 1, 6
date(Field name)Wraps a date value of any type including string and turns it into an object of JODA time type.
withTimezone(date, timeZone ID)Returns a Date, transposing it to the indicated timezone. Timezones are indicated by ID. For example, withTimezone(date(e_responsedate), 'CET'). Note how date() is used to convert the field into an accepted date type object.
now()Returns a JODA time (date object) representation of now. For example:
var d1 = now()
formatDate(date, format)Return the given date formatted according to the given DateFormat pattern. For example, this returns '2006/11/15 14:50:12.222'.
formatDate(new Date(), 'yyyy/MM/dd HH:mm:ss.SSS'
day_of_week(date1, date2)Checks which days of the week are between the two given dates, it returns 1 if weekdays only, 2 if weekend only, 3 if both. For example, this returns 1:
var d1 = new Date(2013, 4, 16);
var d2 = new Date(2013, 4, 18);
day_of_week(d1, d2)

While this returns 3:

var d3 = new Date(2013, 4, 16);
var d4 = new Date(2013, 4, 20);
day_of_week(d3, d4)
formatMsecs(number, TimeUnit)Returns a number of milliseconds formatted to a more readable time length. For example, this returns 1 minute:
formatMsecs(60000)
timeInterval(String timeGrouping, Date date)Returns the name of the TimeInterval that corresponds to the given timeGrouping name and the given Date.
Restriction: To use this function set SlugAvailability to "Export only". For information see K-fields.

Functions that deal with the current survey record

FunctionDescription
seqnum(Field name)Returns the sequence number of the given alternative. For example:

seqnum(q_ov_accommodation) returns 1

numeric(Field name)Returns the numerical value of the given alternative, otherwise "null". For example:

numeric(q_ov_service)

coalesce(object1, object2 ...)Returns first of the objects that is not null. For example:

var a = null;\nvar b = 30;\ncoalesce(a, b) returns 30

intFromPossibleEnum(Field name)Return the ordinal of enum or number. For example:

intFromPossibleEnum(e_status)

text(Field name)Return the static text representation of the value of a field. For example:

text(q_primary_purpose)

name(Field name)Return the name associated to an alternative. For example:

name(e_unitid)

unit(Identifier)Returns the unit with the given identifier. For example: unit('Wilmington').
lookup(lookup table, object)Return values of a lookup table corresponding to the provided keys. The keys must be written in the form of a JavaScript object, such as: lookup('people', { firstname : 'Foo', lastname: 'Bar'}).

If the table contains only one key, you can use a single string instead of an object.

lookupSingle(lookup table, object, field)Returns the values of the lookup table field corresponding to the provided key and field. The key must be written in the form of a JavaScript object, such as: lookupSingle('employee_email', {id: empID}, 'email').
list(value1, value2 ...)Creates a list (array) from a set of values. It ignores null values and automatically flattens values that are already arrays.

Array methods

FunctionDescription
array.length()Returns the number of elements in an array.
array1.concat(array2)Creates a new array, resulting from joining the two arrays into one.
array.filter(condition)Creates a new array, including only the elements that evaluate to TRUE against the condition.
array.indexOf(value)Searches the array for the provided value and returns the array index (0 based) for that value. If the value can't be found in the array, it returns -1.
array.join(separator character)Returns a single string, composed of all of the elements in the array joined into one single value. The elements are separated by the separator indicated in the parameter, a comma is the default.
array.map(function)Creates a new array, containing the results of calling a function for each element in the array. For example, numbers.map(Math.sqrt).
array.reduce(function)Reduces the array to a single value, performing a function to aggregate the values.
array.reverse()Reverses the order of the elements in the array.
array.slice(start index, end index)Returns a section of the array, based on array index positions for the start and end.
array.sort()Orders the contents of an array numerically or alphabetically, either ascending or descending. Numbers are evaluated digit by digit so 21 is considered larger than 100. An optional parameter can set a function through which to compare the values.
array.splice(index, how many, value1,value2...)This method adds or removes elements from an array and returns the removed items. The first parameter defines in what position to start (negative numbers start from the end), the second parameter how many items to remove (may be 0 to just add to the array), and the rest of the parameters are values to add.

Other functions

FunctionDescription
parseInt(text variable)Parses a text field into integer values for calculations.
Tip: It is best practice to wrap a field in text() when you want to use its text value.

JavaScript functions for R-fields

For more information about configuring R-fields, see R-fields.

FunctionDescription
goal(String goalValueType)Calculates the absolute value of the goal given its value type (goal or threshold where X is 1-based).
aggregateUnique(Field name)Return the sample counts for the possible values of the given field.
Important: Be especially judicious about using cube.agregateUnique functions in R-field JavaScript. In split queries, Experience Cloud returns a maximum of 1.5 million splits. Using cube.agregateUnique in an R-field can result in splits far greater than the maximum, especially when multiple cube.aggregateUnique functions are used in the same JavaScript calculation.

JavaScript in surveys

JavaScript can be executed in surveys as part of preconditions and postconditions of any element in a survey. It can also be executed embedded in an HTML component. Most JavaScript functions are allowed in these, but certain functions are intentionally forbidden.

The Fields object can be referenced from a survey. This object can access the values that are present in the survey record and also change them. Below are some of the most common methods for that object:

MethodDescription
fields.get(f)Fetches the text value of the In survey property of field f.
fields.set(f, v)Sets the value for field f to v.
fields.isValid(f, v) Checks if the value v is valid for field f (returns true or false).
fields.getAltById(f, id)Returns the alternative key for the given alternative id. Returns the input ID for non-AltFields and null for invalid IDs.
fields.getAltByName(f, name)Returns the alternative key for the given alternative name. Returns the input id for non-AltFields and null for invalid names.
Restriction: Support for jQuery in Surveys was deprecated beginning with the July 2025 release, and will be completely removed by early 2027. Surveys currently using jQuery selectors like $(dom-selector).action() may not function correctly and could cause custom HTML to render improperly. jQuery is not available in instances not already using it.

Methods of the Cube object

In JavaScript, the object that handles the slug is under the name cube. Several methods can be called from an instance of this object, type cube. Click Control + Space in the JavaScript editor to see suggested cube methods.

Aggregation cube methods that return a single value:

Restriction: cube min and max methods only support numerical values. You can use DateTime fields as arguments for ordering in max or min, but they do not return a DateTime value.
Cube MethodDescription
cube.aggregateUnique(Field name)Return the average of averages. First calculates the average on each field value, and then the average of those averages.
cube.cutValue(List<String> fields)Return the value that was cut on the given fields in this cube.
cube.field(Field name).getSum()Return the sum of the selected field.
cube.getCount()Number of sample values in the cube. It may be a fraction if weights are in use.
cube.getAvg(Field name)Return the average of the values of the fields selected in the cube.
cube.getOuterCutField()Return the outer field this cube was cut.
cube.getOuterCutValue()Return the value of the outer field that this cube was cut on.
cube.getOuterCutValueSingle()Return the value that was cut on the given field in this cube. Which must be a single object.
cube.getNumDaysInTimePeriod()Return the number of days in the timeperiod in the cube.
cube.getNumRecords()Return the number of records in the cube.
cube.getArgument(String key)Get argument passed.
cube.getImplicitUnit()Resolves the unit the cube was filtered by. If it was not filtered by a unit, it returns "null".
cube.getUnitsByUnitGroup(String unitGroup)Get all the active units for the current company.
cube.max(Field name)Return the maximum value of the selected field in the cube.
cube.min(Field name)Return the minimum value of the selected field in the cube.

Methods that return a smaller cube

Cube MethodDescription
cube.cut(Field name, String values)Cuts a slice of the cube by a field and the given values. For example, cube.cut('e_status', 'COMPLETED') selects only samples with the value COMPLETED for the field e_status.
cube.cutObject(Field name, Collection<? extends Object> value)

Cuts a slice of cube by a field in the given values.

cube.cutIfPresent(Field name, String... values)

Cuts the cube on a field and the given values, ignoring the invalid values.". For example, cube.cut('e_status', 'COMPLETED', 'foo').

cube.field(Field name)Selects the given field, which can be either a regular field (e, q, k) or an r-field. In the former case an aggregation method (e.g. count or avg) must be used to obtain a numeric result. For example, cube.field('q_ov_experience').count.

When using R-fields, it may return a number directly with no need for an aggregation.

cube.fieldNotNull(Field name, String... fields)Filters the cube by samples which are not null in the given fields.
cube.fieldNull(Field name1, Field name2)Filters the cube by samples which are null in the given fields.
cube.getOuter()Removes the 'outer' cut value from this cube.
cube.value()Returns a cube containing records that contain the specified value(s) for the currently selected field, such as cube.value('7').

Records may have either of these values: cube.value(['8','9','10']))

Other methods that return a cube

Cube MethodDescription
cube.uncut(Field name)Remove a cut on the given field. Useful if the cube has been sliced on fields A and B but a cube sliced on C and B is needed.

List multiple fields to uncut them all in a single method.

cube.uncut(List<String> fields)Remove a cut of several fields from this cube.
cube.uncutIfPresent(Field name)

Remove a cut from this cube if one exists. Useful for creating columns in a report that do not change even if filters in the OptionBox are selected.

cube.outer()Filters the cube by samples that are null in the given fields.
cube.calc(Field name)Apply the current calculation method on the given field.
cube.fields(Field name1, Field name2, ...)Select multiple fields from the cube.
cube.recut(uncutField name, cutField name)Replace the cut on the first field with the second field. For example, recut('e_creationdate', 'e_responsedate').

Methods that only work on custom modules

Certain cube methods can only be used in the context of Custom modules (AA2 reports), and cannot be used in other types of reports. Below is an example of a cube method being called on one of these reports:

<field-split css-class="tatal nowrap" text="Assist" fields="q_re_macys_assisted">
    <js-calculation eval="cube.percentYes - cube.timeperiodDropdownYearAgo.percentYes" />
    <timeperiod-dropdown-split year-ago="true" />
</field-split>
Tip: To work with the cube on R-fields, unselect the Disable validation option on the new R-field screen.
Cube methodDescription
cube.timeperiod(Field name, String dateField)Selects samples within a timeperiod, according to the date field specified (for example, responsedate). Note that the timeperiod must be of type Analytics Report with a label specified in the Label field.
cube.timeperiodYearAgo(Field name, String dateField)Selects samples within the period that goes from a year before the timeperiod specified up to that period. You can also provide a specific date as a parameter to limit the timeperiod from one year before the provided date to the provided date.
cube.timeperiodDropdownYearAgo()Shows the data from a year before the timeperiod selected in the dropdown (must specify the year-ago="true" attribute in your timeperiod-dropdown-split).
cube.benchmarkIntersection(Field name)Return The cube with the benchmark intersection with the given label applied to the given cube. Works off of benchmark intersection specified in Reporting > Report Helpers > Benchmark Intersections.
cube.fieldNotNull(Field name)Filters samples to avoid data from surveys that have a null value for the provided field.
cube.percentYes()Calculates the percentage of answers that are Yes for a field.
cube.timeperiodDropdown()Selects the data from a timeperiod specified in the dropdown.
cube.field('fieldName').max('lastField')

Returns the fieldName value associated with the lastField with a greater value present in the cube. For example, cube.field('q_ov_experience').max('e_bp_wm_client_aum_int').

cube.field('fieldName').min('lastField')

Returns the fieldName value associated with the lastField with a lesser value present in the cube. For example, cube.field('q_score').min('e_bp_wm_client_aum_int').

cube.field('fieldname').setNpsCalc()

Executes the NPS calculation after the rest of the report is rendered and is called elsewhere in a .calc() function. In this way, it's possible to have different calculations on each row and still do benchmarks on the columns.

Methods that are executed later

When a Custom module is loaded, first the columns in the report are computed, then the rows. There may be specific cases where the results of calculations in the rows are needed by calculations from the columns. For these special cases, the following set of methods exists that has a delayed execution, ensuring that the values from the rows will be available.
Cube methodDescription

cube.setAvgCalc()

Execute an average calculation after the rest of the report is executed.

cube.setSumCalc()

Execute a sum calculation after the rest of the report is executed.

cube.setCountCalc()

Execute a count calculation after the rest of the report is executed.

cube.setTopboxCalc()

Execute calculation of the topbox score after the rest of the report is executed.

cube.setNpsCalc()Sets NPS as the calculation for this cube. Which can be obtained using calc() method.
cube.setPercentYesCalc()Sets the percentage of "Yes" values as the calculation for this cube.