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 restructuring.

It is denoted by three dots (...) and can be used in a variety of contexts, such as function calls, array literals, and object literals.

Spread operator JavaScript

Simple example code expands or spreads an iterable or an array.

<!DOCTYPE html>

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





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'];


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

Spread Operator with Object

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

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

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


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

One of the most common use cases of the spread operator is to pass multiple arguments to a function. Instead of passing an array of arguments, the spread operator can be used to expand the array into individual arguments.

function myFunction(param1, param2, param3) {
  console.log(param1, param2, param3);

const myArray = [1, 2, 3];

myFunction(...myArray); // Output: 1 2 3

It can also be used to pass the properties of an object to another object.

const obj1 = { foo: 'bar', baz: 'qux' };
const obj2 = { ...obj1, quux: 'corge' };

console.log(obj2); // Output: { foo: 'bar', baz: 'qux', quux: 'corge' }

The spread operator can simplify and enhance the readability of code, as well as make it easier to work with data structures.

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 *