Skip to content

Spread operator JavaScript | Basics

  • by

Using the JavaScript spread operator (...) you can copy all or part of an existing array or object into another array or object. The spread operator is often used in combination with destructuring.

Spread operator JavaScript

Simple example code expand or spread an iterable or an array.

<!DOCTYPE html>
<html>
<body>

  <script>
   const arrValue = ['My', 'name', 'is', 'Jack'];

   console.log(arrValue);   
   console.log(...arrValue);

 </script>

</body>
</html> 

Output:

Spread operator JavaScript

Copy all or part of an existing array or object into another array or object.

const n1 = [1, 2, 3];
const n1 = [4, 5, 6];
const res = [...n1, ...n2];

Copy Array Using Spread Operator

const arr1 = ['one', 'two'];
const arr2 = [...arr1, 'three', 'four', 'five'];

console.log(arr2);

Output: [“one”, “two”, “three”, “four”, “five”]

Spread Operator with Object

Adding (Concat) two object (add members obj1 and obj2 to obj3).

const obj1 = { x : 1, y : 2 };
const obj2 = { z : 3 };

const obj3 = {...obj1, ...obj2};

console.log(obj3);

Output: {x: 1, y: 2, z: 3}

Do comment if you have any doubts or suggestions on this JS Spread topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.