Why use spread operator when sorting an array in JavaScript?

In summary, the spread operator is used to efficiently create a copy of an array, as shown in the conversation. It allows for the individual elements of the array to be spread out rather than creating a new array with the original array as its only element. This is why the output differs when the spread operator is not used. The use of the spread operator is not required in the code, but it is a more efficient and preferred method for creating a copy of an array.
  • #1
shivajikobardan
674
54
TL;DR Summary
spread operator javascript
I Understand the basic theory behind spread operator.

JavaScript:
const girlNames = ['Jessica', 'Emma', 'Amandine']
const newGirlNames = [...girlNames]
console.log(newGirlNames)
// Output: ["Jessica", "Emma", "Amandine"]

But I don't understand when it's applied. See here.

JavaScript:
function createList() {
  [...richestPeople]
    .map(a => ({ value: a, sort: Math.random() }))
    .sort((a, b) => a.sort - b.sort)
    .map(a => a.value)
    .forEach((person, index) => {
      const listItem = document.createElement("li");
      listItem.setAttribute("data-index", index);
      listItem.innerHTML =
        `
    <span class="number">${index + 1}</span>
    <div class="draggable" draggable="true">
    <p class="person-name">${person}</p>
    <i class="fa-solid fa-grip-lines"></i>
    </div>

    `

      listItems.push(listItem);
      draggable_list.appendChild(listItem);
    })
}

Why do we require spread operator here? I tried to see the output w/o spread operator and seeing that didn't help.
output with spread operator:
1673710726254.png


output without spread operator:
1673710757527.png


It must be obvious to people, but it's not to me. I'm not getting it.
 
Technology news on Phys.org
  • #2
This suggests that [...arr] is an efficient way of creating a copy of the one-dimensional array arr. Without the operator, you have [arr], an array consisting of a single entry, namely arr. Hence your second screenshot has the entire list of names as a comma-separated string in a single <li> tag, rather than each name in its own <li> tag as in the first screenshot.
 
Last edited:
  • #3
shivajikobardan said:
JavaScript:
function createList() {
  [...richestPeople]
    .map(a => ({ value: a, sort: Math.random() }))
    // ...
}
Why do we require spread operator here? I tried to see the output w/o spread operator and seeing that didn't help.
You don't. The code below has exactly the same result.
JavaScript:
function createList() {
  richestPeople
    .map(a => ({ value: a, sort: Math.random() }))
    // ...
}
But note
JavaScript:
function createList() {
// This sorts the array richestPeople.
richestPeople.sort();
// This creates a new array of the elements of richestPeople and sorts it.
// richestPeople is left unsorted.
sortedRichestPeople = [...richestPeople].sort();
// This code has an identical result and is preferred by some:
sortedRichestPeople = richestPeople.slice().sort();
 

What is the spread operator in JavaScript?

The spread operator in JavaScript is an ES6 feature that allows us to expand or spread elements of an iterable (such as an array) into individual elements. It is denoted by three consecutive dots (...).

How does the spread operator work?

When used on an iterable (such as an array), the spread operator will expand the elements of the iterable into individual elements. This allows us to easily combine or copy arrays, or pass individual elements as arguments to a function.

What is the difference between the spread operator and the rest parameter?

The spread operator and the rest parameter both use the same syntax (three dots), but they have different purposes. The spread operator expands an iterable into individual elements, while the rest parameter collects individual elements into an array.

Can the spread operator be used on non-iterable objects?

No, the spread operator can only be used on iterable objects such as arrays, strings, or objects with a Symbol.iterator method. Trying to use it on a non-iterable object will result in an error.

What are some use cases for the spread operator?

The spread operator can be used for various purposes such as copying arrays, merging arrays, passing arguments, and creating new arrays or objects. It is also commonly used with functions like Math.max() to find the maximum value in an array.

Back
Top