Spread Operator

The spread operator (denoted as three dots ...) expands an iterable variable (such as an array of numbers, strings or orjects) into its individual elements. The spread operator can be used to make a copy of an iterable variable.    

An example showing the spread operator (Run Example)

<!DOCTYPE html>
<html>
    <head>
        <title>... spread operator example</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

    </head>

    <body>
        <h1>Press F12 to view the output in the Browser console </h1>
                     
        <script>
            const numbers = [1, 2, 3]

            console.log(...numbers)    // expected output: 1 2 3                          
        </script>
    </body>
</html>

 

 

In order to make a copy of an array, we need to spread the variables inside the new array's [] brackets, as shown in the example below.

An example showing how the spread operator can be used to make a copy of an array (Run Example)

<!DOCTYPE html>
<html>
    <head>
        <title>...spread operator copy example</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

    </head>

    <body>      
        <h1>Press F12 to view the output in the Browser console </h1>
               
        <script>
            const names = ["Anne", "Brian", "Cathy", "David"]

            let copyOfNames = [...names]
            console.log(copyOfNames) // expected output is an array containing the values "Anne", "Brian", "Cathy", "David"
        </script>
    </body>
</html>

Write code to make a copy of an array of numbers.

 
<div align="center"><a href="../versionC/index.html" title="DKIT Lecture notes homepage for Derek O&#39; Reilly, Dundalk Institute of Technology (DKIT), Dundalk, County Louth, Ireland. Copyright Derek O&#39; Reilly, DKIT." target="_parent" style='font-size:0;color:white;background-color:white'>&nbsp;</a></div>