November 30, 2020
Spread and Rest Operators
Comments
(1)
November 30, 2020
Spread and Rest Operators
Newbie 6 posts
Followers: 3 people
(1)

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 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);

Lets take some examples to simulate the various use-cases, where a developer can use Spread Operator.

Function Call:

<cfscript>
numbers = [1,2,3];
writeDump(sum( ...numbers ));
function sum(required x,required y,required z) {
  return x + y + z;
}
</cfscript>
 
Array Literals:
 
<cfscript>
numbers = [1,2,3];
list = [...numbers,'4','five', 6,...numbers]; // [1,2,3,'4','five',6,1,2,3]
writeDump(list);
</cfscript>
 
The above code will output the following:

String Literals :
<cfscript>
arr = [..."12345","tep",..."ColdFusion","test"];
writeDump(arr);
</cfscript>
 
 
Struct Merge Operation using Spread Operator :
<cfscript>
obj1 ={ foo: 'bar', x: 42 };
obj2 ={ foo: 'baz', y: 13 };
mergedObj1 ={...obj1,...obj2};
writeDump(mergedObj1);
</cfscript>
 
 
Rest Operator : 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.
 
Syntax:
function myFunction(…rest)//…rest is the rest parameter
{}

<cfscript>
function myFun(a, b, ...manyMoreArgs) {
writeDump(a); // Output: "one"
writeDump(b); // Output: "two"
writeDump(manyMoreArgs);// Output : ["three","four","five","six"]
}
myFun("one", "two", "three", "four", "five", "six");
</cfscript>

 
Spread and Rest Operators are very powerful. They can be used to handle complex scenarios by writing short concise code.
Please try it out and let us know the feedback.
1 Comment
2021-05-20 07:25:51
2021-05-20 07:25:51

Cheers for this.

It would be handy if you included a link to the docs for this in the article somewhere, especially given when I google for “coldfusion rest operator”, I get this blog article, but the docs don’t seem to show up at all.

Like
Add Comment