head — GTM Variable Template for Array
head EXTENDED Array
Returns the first item from the input array. Returns undefined if the array is empty or invalid.
Examples
First element
INPUT
Array To Inspect: [1, 2, 3, 4, 5]
OUTPUT
1
Empty array returns undefined
INPUT
Array To Inspect: []
OUTPUT
undefined
GTM Configuration
This is what you'll see when you open this variable in Google Tag Manager. Hover the icons for details.
head
Array To Inspect
💾 The array to get the first item from.
Supported formats:
✓ Array
Supported formats:
✓ Array
Input Setup
Input Function (optional)
⚙️ Optional pre-processing function applied to the input before internal logic (e.g., convert object to string, normalize case). Internal transformations such as case handling will still apply afterward.
Result Handling
Output Function (optional)
⚙️ Optional function to apply to the result before returning it (e.g., str => str + ' €', val => val !== undefined for boolean conversion). Useful for chaining transformations on the output.
Array To Inspect array
💡 Type any text to see the result update live
🎯 Using special value — click input to type instead
Test with:
Falsy
Truthy
🔗 Result Handling — Chain Variables
Chain apply-mode variables to the output. Each variable receives the result of the previous one.
head()
Related Variables
Same category: Array
Under the Hood
📜 View Implementation Code
/**
* Returns the first item of the input array without modifying it.
*
* @param {Array} data.src - The array to inspect.
* @param {Function|string} [data.out] - Optional output handler: function to transform result or string with format.
*
* Direct-mode specific parameters:
* @param {Function} [data.pre] - Optional pre-processor function to transform src before getting first item.
*
* @returns {*} The first item of the array, or undefined if the array is empty or invalid.
*
* @framework ggLowCodeGTMKit
*/
const getType = require('getType');
const head = function(arr) {
if (getType(arr) !== 'array' || arr.length === 0) {
return undefined;
}
return arr[0];
};
const safeFunction = fn => typeof fn === 'function' ? fn : x => x;
const out = safeFunction(data.out);
// ===============================================================================
// head - Direct mode
// ===============================================================================
const applyCast = (castFn, value) => safeFunction(castFn)(value);
const value = applyCast(data.pre, data.src);
return out(head(value));
// ===============================================================================
// head() – Apply Mode
// ===============================================================================
/*
return function(value) {
return out(head(value));
};
*/🧪 View Test Scenarios (5 tests)
✅ '[example] First element'
✅ Array with single item - should return that item
✅ '[example] Empty array returns undefined'
✅ Array with mixed types - should return first item
✅ Non-array input - should return undefined