JavaScript for LWC: Spread Operator

What is Spread Operator ?

Spread Operator introduced in ES6. It’s syntax is (…). It allows to expand or unpack elements of iterable, such as array, set, map and strings. In objects, spread operator iterates over the enumerable properties of the specified object and includes those properties as key value pairs in new object being created. It has several significant use cases and can greatly simplify code in many situations. Spread operator allow us to Copy arrays and objects, concatenating arrays and strings, passing arrays as a function argument, destructuring objects and arrays etc.

Spread Operation on String

It expand the string into individual characters. It returns the array containing characters of string. We can iterate over strings and perform string manipulation.

Expanding String

let str = “Hello LWC”;
let chars = [...str];
console.log(chars);
chars.forEach(char => {
    console.log(char);
});
[
  'H', 'e', 'l',
  'l', 'o', ' ',
  'L', 'W', 'C'
]
H
e
l
l
o
 
L
W
C

String Reversal

let reversedStr = [...chars].reverse().join("");
console.log(reversedStr);
CWL olleH

String Concatenation

const str1 = "Hello";
const str2 = "LWC";
const concatenatedStr = [...str1, ...str2].join("");
console.log(concatenatedStr);
HelloLWC

Use spread operator for concatenation where, you need to manipulate strings as array of characters.

Spread Operation on Array

Combining Array

let arr1 = ["Tiger", "Lion"];
let arr2 = ["Leopard", "Cheetah"];
let arr3 = [...arr1, ...arr2];
console.log(arr3);
[ 'Tiger', 'Lion', 'Leopard', 'Cheetah' ]

Adding values to Array

let arr4 = […arr3, "Puma"];
console.log(arr4);
[ 'Tiger', 'Lion', 'Leopard', 'Cheetah', 'Puma' ]

Shallow Copy

The object and array in JavaScript work as a reference. When we copy or assign one array to other then it copy reference as well.

let arr = ["apple", "orange", "mango"];
let arr1 = arr;
arr1.push("Strawberry");
console.log(arr);
console.log(arr1);
[ 'apple', 'orange', 'mango', 'Strawberry' ]
[ 'apple', 'orange', 'mango', 'Strawberry' ]

When we add strawberry in arr1 it automatically updates or added in arr. Hence, use spread operator to create shallow copy of an array.

let arr = ["apple", "orange", "mango"];
let arr1 = [...arr];
arr1.push("Strawberry");
console.log(arr);
console.log(arr1);
[ 'apple', 'orange', 'mango' ]
[ 'apple', 'orange', 'mango', 'Strawberry' ]

Please note shallow copy works on only one level data structure. It won’t work on complex data structures like array of objects.

var arrOfObj = [
	{name: "JK", age: 40},
	{name: "PM", age:32}
];
var arrOfObj1 = [...arrOfObj];
console.log(arrOfObj1);
arrOfObj1[0].name = “TW”;
console.log(arrOfObj); //TW updated in arrOfObj too
console.log(arrOfObj1);
[ { name: 'JK', age: 40 }, { name: 'PM', age: 32 } ]
[ { name: 'TW', age: 40 }, { name: 'PM', age: 32 } ]
[ { name: 'TW', age: 40 }, { name: 'PM', age: 32 } ]

To solve above problem for nested data structures. You can use stringify() method to convert array of objects to string and then parse it.

var arrOfObj = [
	{name: "JK", age: 40},
	{name: "PM", age:32}
];
let arrOfObj2 = JSON.parse(JSON.stringify(arrOfObj));
arrOfObj2[0].name = "TW";
console.log(arrOfObj);
console.log(arrOfObj2);
[ { name: 'JK', age: 40 }, { name: 'PM', age: 32 } ]
[ { name: 'TW', age: 40 }, { name: 'PM', age: 32 } ]

Passing Array Elements as a function arguments

Using spread operator while calling a function offers several advantages like flexibility with arguments, it avoids mutation, improving performance in some cases compared to apply() method.

function sum(a, b, c) {
    return a + b + c;
}

const numbers = [1, 2, 3];
const result = sum(...numbers);
console.log(result);
6
const dateFields = [2023, 2, 1]; // 1 Jan 1970
const d = new Date(...dateFields);
console.log(d);
2023-03-01T00:00:00.000Z

Spread Operation on Objects

There are two ways to access the values assigned to properties of object dot notation and array notation. If property has space in between then array notation use. Key can be without quotes as well.

var obj = {
	name: "JK",
	age: 25,
    "full name": "JK JK"
}
console.log(obj.name); //25
console.log(obj["age"]);//25
console.log(obj.full name);//error
console.log(obj["full name"]);
JK
25
SyntaxError: missing ) after argument list
JK JK

Combining a Object

var obj = {
	name: "JK",
	age: 25,
    "full name": "JK JK"
}

var obj1 = {
	name: “PM”,
    age: 27,
   	"full name": "PM PM"
}
let obj2 = {...obj , ...obj1}; //use curly braces to spread objects
console.log(obj2);
{ name: 'PM', age: 27, 'full name': 'PM PM' }

If properties in objects are similar on which spread operation is performed then RHS side values will overwrite on LHS values. On the other hand, if the properties in objects are unique then they will add up.

var obj = {
	name: "JK",
	age: 25,
    "full name": "JK JK",
    address: "Baker Street"
}

var obj1 = {
	name: “PM”,
    age: 27,
   	"full name": "PM PM",
   	profession : "Engineer"
}
let obj2 = {...obj , ...obj1}; //use curly braces to spread objects
console.log(obj2);
{
  name: 'PM',
  age: 27,
  'full name': 'PM PM',
  address: 'Baker Street',
  profession: 'Engineer'
}

In conclusion, the spread operator in JavaScript is a versatile tool that offers significant benefits for Lightning Web Component (LWC) development in Salesforce. Its intuitive syntax and powerful capabilities make it a valuable asset for handling arrays and iterable objects efficiently. Whether you’re concatenating arrays, copying elements, adding new elements, passing function arguments dynamically, or converting array-like objects to arrays, the spread operator simplifies these tasks and enhances code readability.

For LWC developers working within the Salesforce ecosystem, understanding and leveraging the spread operator can lead to more concise, maintainable, and performant code. By harnessing its capabilities, developers can streamline array manipulation tasks, improve code organization, and ultimately deliver better user experiences within Lightning components. As Salesforce continues to evolve, mastering JavaScript fundamentals like the spread operator will remain essential for building robust and scalable LWC applications.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *