Skip to main content

(...) What is spread operator in javascript and how to use it

· 2 min read
Parth Maheta

The spread operator (...) in JavaScript is a versatile syntax used for several purposes, such as spreading elements of an array, spreading properties of an object, and more. Let's explore its main uses:

1. Spreading Elements of an Array:

const array1 = [1, 2, 3];
const array2 = [...array1, 4, 5, 6];

console.log(array2); // Output: [1, 2, 3, 4, 5, 6]

In this example, the spread operator is used to create a new array (array2) by spreading the elements of array1 and adding additional elements.

2. Spreading Properties of an Object:

const object1 = { foo: 'bar', baz: 'qux' };
const object2 = { ...object1, age: 25 };

console.log(object2);
// Output: { foo: 'bar', baz: 'qux', age: 25 }

Here, the spread operator is used to create a new object (object2) by spreading the properties of object1 and adding a new property (age).

3. Cloning Arrays and Objects:

const originalArray = [1, 2, 3];
const clonedArray = [...originalArray];

const originalObject = { name: 'John', age: 30 };
const clonedObject = { ...originalObject };

console.log(clonedArray); // Output: [1, 2, 3]
console.log(clonedObject); // Output: { name: 'John', age: 30 }

The spread operator is used here to create shallow copies of both arrays and objects.

4. Concatenating Arrays:

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const concatenatedArray = [...array1, ...array2];

console.log(concatenatedArray); // Output: [1, 2, 3, 4, 5, 6]

Here, the spread operator is used to concatenate two arrays into a new one.

5. Function Arguments:

const displayValues = (a, b, c) => {
console.log(a, b, c);
};

const values = [1, 2, 3];
displayValues(...values); // Output: 1 2 3

The spread operator is used to pass array elements as individual arguments to a function.

6. Rest Parameters:

const addNumbers = (x, y, ...rest) => {
console.log(x + y);
console.log(rest);
};

addNumbers(1, 2, 3, 4, 5);
// Output:
// 3
// [3, 4, 5]

The spread operator is used in function parameters as a rest parameter, collecting remaining arguments into an array.

These are some common uses of the spread operator in JavaScript. It's a powerful and concise syntax that enhances the flexibility of working with arrays and objects.