Salesforce Interview Questions & Answers Book is now available!

Grab Now

LWC

spread operator in LWC

In this post let's look at how to use a spread operator in LWC.

By Teja, ex-Salesforce engineer · Updated March 23, 2021 · 1 min read

In the last post we looked at rest operator and in this post, we will be looking at spread operator in LWC.

Just by the looks of it, you might not be able to understand the difference between rest operator and spread operator.

Rest operator and Spread operator both use the same notation which is ....

However, in you look deeper there is a catch!

Were you able to figure that out?

rest operator is to the left of the equals symbol and spread operator is used to the right of the equals symbol.

Even here instead of showing a snippet of code that makes a call to the Apex method and fetches the information, I will only focus on the snippet and not the boilerplate code.

Let's look at a snippet that uses spread operator!

/* this is an array */
let keywords = ['Krishna', 'Teja', 'Programmer', 'Salesforce'];

/* Here we are trying to add all the elements of first array and 
   and also add new elements to the new array */
let advancedKeywords = [...keywords, 'hiking', 'sneaker head, foodie'];

Snippet using spread operator

Sweet! isn't it?

This will be used when you want to take a deep copy of array and then add new elements on top of it or clone an array etc.

Hope this is helpful!

Learn it by building it

Every course, every code repository, the discussion group and certificates of completion — one subscription.

Keep me in the loop!

Email me when a new episode is published (promise, I will not spam you)

You're signing up to receive emails from Salesforce Casts