What is Spread Element in JavaScript and how to spread an iterable?

This video covers what is a Spread Element in JavaScript (ES6) and how to spread an iterable and use it in function calls.

Spread element is also useful to solve problems like Insert array in the middle of another array in JavaScript.

Code

// Spread An Array
let userNames = ['amy24', 'sam67', 'tero99', 'bonsaii', 'deeksha25'];
let allUserNames = [...userNames, 'tazo', 'rama01']
console.log(allUserNames);
// Spread A String
let message = 'I love JS';
let spreadMessage = [...message];
console.log(spreadMessage);
// Spread A Set
let toolSet = new Set();
toolSet.add('hammer');
toolSet.add('nails');
toolSet.add('driller');
let spreadToolSet = [...toolSet];
console.log(spreadToolSet)
// Spread A Map
let idToName = new Map();
idToName['12hj3']= 'Deeksha';
idToName['445fg']= 'Bonsaii';
idToName['99hjy']= 'Amy';
let newIdToName = {...idToName};
console.log(newIdToName);
// Spread An Object
let user = {
name: 'Deeksha',
username: 'deeksha25',
interests: ['sketching', 'code', 'videos', 'book-reading']
}
let newUser = {...user};
console.log(newUser);

Full Transcript

00:00 Hi everyone. Welcome to the JavaScript series and I'm Deeksha Sharma from bonsaiilabs. Today we are going to learn what is spread element in JavaScript and how to spread iterable and use it in function calls. So what is a spread element? Spread element in JavaScript is used to expand all the elements out of an iterable. Now iterable could be the built-in ones provided by JavaScript such as array, String, map and set. But spread element also allows expansion of key value pairs from an object expression. It could be used wherever key value pairs are expected. There is an important difference here. Objects in JavaScript are not iterable, which means as opposed to built-in iterables, object do not implement iterator method. Spread properties would introduce to object literals in ES6. Let's now look at the syntax. The three dots in front of an iterable represents the spread element in JavaScript.

00:54 The way it is used with Array literals is by putting three dots in front of an array, string or a set and spreading it inside an array literal expands all the elements inside them. Since JavaScript spread element also expands JavaScript objects, this is how any object could be spread at places that expect key value pairs. Now map also contains key value pairs, so applying spread operator in front of a map object also expands and open up its entries. Finally, spread element could also be used in function calls. Instead of writing every single argument to myFunction, we can spread an array of arguments using this short syntax. I'm sure looking at the syntax wasn't enough, so let's go over an example of spreading the arrays. We have a userNames array containing a couple of usernames. There is another variable spreaduserNames which expands all elements inside userNames array.

01:45 When we logged the value of spreadUserNames, it spreads out all the elements from userNames and put them in the new array. Let's look at another variable message that holds a string "I love JS". String is nothing but an array of characters, so we can similarly spread a string inside an array literal. Now when we log the value of spreadMessage array, it gives us back this output. Did you notice that every character is spread as a separate element in the spreadMessage array. Another JavaScript built-in iterable is the set that stores unique values. So let's say we have a variable toolSet and we add a hammer, nails and driller inside the set using the add method. We then try to spread toolSet inside this new array spreadToolSet and log its value. As a result, we get this output.

02:27 All the elements of the set are spread in this new array. You may have noticed a pattern that all spreads syntax does is it opens up all the elements contained inside the original iterable. Spread syntax can also spread the entries of a map in JavaScript. Here is an example - idToName is a variable that holds a map and we add three entries to it. Each entry has a key which is an ID and its value, which is name. We have another variable, newIdToName. It's an object which accepts key value pairs so we can pretty much spread idToName here. Now the map idToName is nothing but a collection of key value pairs containing IDs and the names, so when we apply spread syntax, it expands and open up all the entries here in this object. Logging its value gives us the entries similar to the map, just that newIdToMap is not a map but an object.

03:17 Now that you saw how spread works on map, it works exactly same for JavaScript objects. Let's consider this user variable which holds an object containing user information including name, username, and an array of user interests. Similar to the map example, we declare a newUser object and initialize it by spreading everything that's inside the user object. Logging its value, we'll print all the user entries that are now part of newUser object. Finally, we can also use spread syntax in function calls. Let's say we have this function printUserInfo that takes three arguments, firstName, lastName and the address. It then simply logs the values of these arguments on console. Next, we have an array info containing three elements - first name Deeksha, last name Sharma and an address Canada. Now when we call printUserInfoFunction(), instead of passing three arguments to it, we use the spread syntax on info array.

04:09 It expands all the elements from the array in the same sequence for the function to use. And here is the output after printUserInfoFunction is executed. So that's it for this video. In the next one, I'll be covering some use cases specific to arrays and objects where spread element could be useful. So be sure to check it out. Thank you so much for watching and if you have any questions, drop the comments. You can also ask for a topic to be covered and I will add them in the future videos. Subscribe to this channel if you haven't already. Until then, my friends keep learning and share your knowledge.