Skip to content

๐Ÿงฉ IF ELSE IF (Predefined) โ€” GTM Variable Template for Logic

VARIABLES โ€บ LOGIC
๐Ÿงฉ IF ELSE IF (Predefined) EXTENDED Logic

IF-ELSE-IF logic with predefined comparison operators (equals, contains, starts with, regex, numeric). Returns first match or default value.


Examples

Equals match
INPUT
Params Table: [
{
"Input Value":
"hello",
"Condition": "eq",
"Reference Value": "hello",
"Output Value": "Match 1"
},
{
"Input Value":
"world",
"Condition": "eq",
"Reference Value": "world",
"Output Value": "Match 2"
}
]

Default Output:
No match
OUTPUT
Match 1
No match returns default
INPUT
Params Table: [
{
"Input Value":
"hello",
"Condition": "eq",
"Reference Value": "goodbye",
"Output Value": "Match 1"
},
{
"Input Value":
"world",
"Condition": "eq",
"Reference Value": "earth",
"Output Value": "Match 2"
}
]

Default Output:
Default value
OUTPUT
Default value

GTM Configuration

This is what you'll see when you open this variable in Google Tag Manager. Hover the icons for details.

๐Ÿงฉ IF ELSE IF (Predefined)
IF ELSE โฌ‡
Params Table
๐Ÿ’ก Tips:
โ€ข Order matters! Conditions are checked from top to bottom
โ€ข First match wins - remaining conditions are skipped
โ€ข Use specific conditions first, general conditions last
โ€ข Combine operators: starts with (case insensitive) for flexible matching
Input ValueConditionReference ValueOutput Value
โŠ–
โŠ–
ELSE โฌ‡
Default Output
๐Ÿ“ค The value to return if none of the conditions match.

This is the "ELSE" in the IF-ELSE-IF-ELSE logic.

If left empty, returns undefined.

Examples:
โ€ข Unknown
โ€ข 0
โ€ข {{Fallback Variable}}
Result Handling
Output Function (optional)
โš™๏ธ Optional function to transform the final output before returning it.

Applied to both matched condition outputs and the default output.

Examples:
โ€ข str => str.toUpperCase() โ†’ Convert to uppercase
โ€ข val => val + ' โ‚ฌ' โ†’ Append currency
โ€ข val => parseInt(val) โ†’ Convert to integer
โ€ข val => val || 'N/A' โ†’ Fallback for empty values

Useful for chaining transformations or ensuring consistent output format.
Params Table table
Input ValueConditionReference ValueOutput Value
Default Output string
ifElseIf()


Under the Hood

๐Ÿ“œ View Implementation Code
/**
 * Evaluates conditions sequentially using IF ELSE IF logic.
 * Returns the value of the first matching condition, or default if none match.
 *
 * @param {Array<Object>} ls1 - Array of condition objects with values to return.
 * @param {*} def - Default value to return if no conditions match.
 *
 * @returns {*} The value of the first matching condition, or default value.
 *
 * @framework ggLowCodeGTMKit
 */
const makeNumber = require('makeNumber');

const ifElseIf = function(ls1, def) {
    const toStr = function(val) {
        if (val === null) return 'null';
        if (val === undefined) return 'undefined';
        return typeof val === 'string' ? val : val.toString();
    };

    const toLower = function(str) { return str.toLowerCase(); };

    const convertToNumber = function(value) {
        if (typeof value === 'number') return value;
        if (typeof value !== 'string') return value;
        const num = makeNumber(value);
        return (typeof num === 'number' && num === num) ? num : value;
    };

    const ruleMethods = {
        eq: function(val, ref) { return val == ref; },
        ct: function(val, ref) { return val.indexOf(ref) > -1; },
        sw: function(val, ref) { return val.substring(0, ref.length) === ref; },
        ew: function(val, ref) { return val.substring(val.length - ref.length) === ref; },
        re: function(val, ref) { return val.search(ref) !== -1; },
        xlt: function(val, ref) { return val < ref; },
        xlte: function(val, ref) { return val <= ref; }
    };

    const evaluateCondition = function(cond) {
        if (!cond) return false;

        const condKey = cond.con || '';
        if (condKey.length === 0) return false;

        const firstChar = condKey[0];
        const lastChar = condKey[condKey.length - 1];

        const isNegated = firstChar === 'n' && condKey.length > 1;
        const isInsensitive = lastChar === 'i' && condKey.length > 1;

        const baseStart = isNegated ? 1 : 0;
        const baseEnd = isInsensitive ? condKey.length - 1 : condKey.length;
        const baseCondition = condKey.substring(baseStart, baseEnd);

        const ruleFn = ruleMethods[baseCondition];
        if (!ruleFn) return false;

        var val = cond.val;
        var ref = cond.ref;

        const isNumericRule = baseCondition[0] === 'x';

        if (isNumericRule) {
            val = convertToNumber(val);
            ref = convertToNumber(ref);
        } else {
            val = toStr(val);
            ref = toStr(ref);

            if (isInsensitive) {
                val = toLower(val);
                ref = toLower(ref);
            }
        }

        const result = ruleFn(val, ref);
        return isNegated ? !result : result;
    };

    // Sequential IF-ELSE-IF evaluation
    const rules = ls1 || [];
    for (var i = 0; i < rules.length; i++) {
        var rule = rules[i];
        if (!rule) continue;

        // Support both nested {condition: {val, con, ref}, res} and flat {val, con, ref
๐Ÿงช View Test Scenarios (27 tests)
โœ… '[example] Equals match'
โœ… Second condition matches (first fails)
โœ… '[example] No match returns default'
โœ… Case insensitive equals (eqi)
โœ… Contains (ct)
โœ… Not contains (nct)
โœ… Starts with (sw)
โœ… Ends with case insensitive (ewi)
โœ… Regex match (re)
โœ… Numeric less than (xlt)
โœ… Numeric not less than (nxlt = greater than or equal)
โœ… Multiple conditions with priority (first match wins)
โœ… With output function
โœ… Empty rules array returns default
โœ… Invalid condition (missing operator) skips to next
โœ… null is stringified for string comparison
โœ… undefinedis stringified for string comparison
โœ… boolean true is stringified for string comparison
โœ… boolean false is stringified for string comparison
โœ… number becomes string for string comparison
โœ… null in contains operation
โœ… String 10 vs number 10 in numeric comparison (both converted)
โœ… Number in string operation (toString called)
โœ… Boolean in contains (true โ†’ string true)
โœ… Numeric comparison with non-numeric string (stays as is)
โœ… Reference value stringification (ref with boolean)
โœ… Both val and ref are null