Copyright Derek O'Reilly, Dundalk Institute of Technology (DkIT), Dundalk, Co. Louth, Ireland.
The spread operator (denoted as three dots ...) expands an iterable variable (such as an array of numbers, strings or objects) 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.
Copyright Derek O' Reilly, Dundalk Institute of Technology (DkIT), Dundalk, Co. Louth, Ireland.