Monday 28 June 2021

CFML: function expression syntax

G'day:

Just super quickly. One of the newer feaures in CFML is that it now supports arrow-function syntax for function expressions. I say "newer". They were apparently added to ColdFusion in 2018, and they're in Lucee: I dunno from what version.

I've been using arrow functions a bit in my code recently, cos they're just less typing for no loss of clarity compared to function expressions using the function operator. in case yer not used to them, these two code snippets are functionally equivalent:

adder = function(operand1, operand2) {
    return operand1 + operand2
}


adder = (operand1, operand2) => {
    return operand1 + operand2
}

Arrow functions offer some shortcuts though. If the body of the function is a single expression and it's the returned value, then one doesn't need to specify the block braces, or the return keyword. So the above arrow function could simply be:

adder = (operand1, operand2) => operand1 + operand2

What's more, if the function expression has only parameter, then one doesn't even need to specify the parentheses:

double = operand1 => operand1 * 2

(this is currently broken on Lucee: https://luceeserver.atlassian.net/browse/LDEV-2417).

There's no tag-based equivalent of either syntax for function expressions. That said, if one does not care about the closure side of things that function expressions utilise (and neither of these examples do), then the two function expressions above are equivalent to these two <cffunction>-based function statement declarations:

<cffunction name="adder">
    <cfargument name="operand1">
    <cfargument name="operand2">
    <cfreturn operand1 + operand2>
</cffunction>
<cffunction name="doubLe">
    <cfargument name="operand1">
    <cfreturn operand1 * 2>
</cffunction>

In reality though, these are closer to these equivalent statements in CFScript:

function adder(operand1, operand2) {
    return operand1 + operand2
}

function double(operand1) {
    return operand1 * 2
}

The difference is that these are statements, not expressions.

OK. That's enough bloody CFML tags for one evening.

Righto.

--
Adam