Copy link to clipboard
Copied
Operators define a quick way of implementing complex functionality with a short concise easy to use syntax. ColdFusion exposes multiple operators to ease out the complex operations. With this objective in mind, we have introduced the Spread and Rest Operators.
Spread Operator
Spread Operator: Spread Operator allows an Iterable Object(Array/Struct/String) to be expanded into individual elements. The Spread Operator is represented by Three Dots (…).
Syntax
Array Literals : […iterableObject, 2021, …"ColdFusion"]
Object Literals : clonedObject = {…Object}
Function Calls : result = setFunctionValues(…iterableObject)
Let’s start off with an example to show the Spread operator works.
<cfscript>
numbers = [1,2,3];
writeDump(sum( ...numbers ));
function sum(required x,required y,required z) {
return x + y + z;
}
</cfscript>
Output
6
The Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected.
<cfscript>
myarray1=[5,6,7]
myarray2=[3,4,5,...myarray1]
myarray3=[1,2,3,...myarray2]
writedump(myarray3)
</cfscript>
Array Literals
<cfscript>
numbers = [1,2,3]
list = [...numbers, '4', 'five', 6,...numbers]
writeDump(list)
</cfscript>
String Literals
<cfscript>
arr = [..."12345","foo",..."bar",..."123"];
writeDump(arr)
</cfscript>
Merge iterable objects
<cfscript>
s1=["Mick Jagger"]
s2=["Keith Richards","Ron Wood"]
s3=["Charlie Watts"]
// merge the arrays using Spread
stones=[...s1,...s2,...s3]
writeDump(stones)
</cfscript>
Object Literals
<cfscript>
foo={
"key1":"val1",
"key2":"val2",
"key3":"val3"
}
bar={
"key4":"val4",
"key5":"val5"
}
combo={...foo,...bar}
writeDump(combo)
</cfscript>
Rest Operator
The Rest operator operator is similar to Spread Operator but behaves in opposite way, while Spread syntax expands the iterables into individual element, the Rest syntax collects and condenses them into a single element.
For example,
<cfscript>
function myRest(...args){
writeDump(args)
}
myRest(1,2,3,4,5)
</cfscript>
Another example
<cfscript>
function myFun(a,b,...otherArgs){
writeOutput(serializeJSON(a))
writeOutput(serializeJSON(b))
writeOutput(serializeJSON(otherArgs))
}
myFun("one","two","three","four","five","six","seven","eight")
</cfscript>
Further reading
Have something to add?