spread operator

The spread operator (...) in JavaScript is a versatile and powerful feature that allows you to expand or spread elements in arrays, objects, or function arguments. It’s commonly used for copying, merging, and passing around data structures without modifying the original ones.

the use of spread operator in Array

Copying an Array:


const arr1 = ["Apple","Banana", "Orange"];
const arr2 = [...arr1];
console.log(arr2); // Output: [Apple,Banana,"Orange]

Combining Arrays


const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined); // Output: [1, 2, 3, 4, 5, 6]

Adding Elements to an Array:


const arr1 = [1, 2, 3];
const arr2 = [0, ...arr1, 4];
console.log(arr2); // Output: [0, 1, 2, 3, 4]

the use of the spread operator in Object

Copying an Object


const obj1 = { name: 'John', age: 38 };
const obj2 = { ...obj1 };
console.log(obj2); // Output: {name: 'John', age: 38}

Merging Objects


const obj1 = { name: 'John', age: 38 };
const obj2 = { sex: 'Male', qualification: 'Graduate'};
const merged = { ...obj1, ...obj2 };
console.log(merged); // Output: {name: 'John', age: 38, sex: 'Male', qualification: 'Graduate' }

Overriding Properties


const obj1 = { name: 'John', age: 38 };
const obj2 = { age: 39, qualification: 'Graduate'};
const merged = { ...obj1, ...obj2 };
console.log(merged); // Output: {name: 'John', age: 39, qualification: 'Graduate' }

Function Arguments

Spreading an Array as Arguments


function sum(a, b, c, d) {
  return a+b+c+d;
}
const numbers = [1, 2, 3,4];
console.log(sum(...numbers)); // Output: 10

spread operator – Interview Questions

Q 1: What is the spread operator?

Ans: It expands iterable elements.

Q 2: Syntax of spread operator?

Ans: ....

Q 3: Can it copy arrays?

Ans: Yes (shallow copy).

Q 4: Can it merge objects?

Ans: Yes.

Q 5: Is the spread operator an ES6 feature?

Ans: Yes.

spread operator – Objective Questions (MCQs)

Q1. The spread operator is represented by ______.






Q2. The spread operator is used to ______.






Q3. Which data type can use the spread operator?






Q4. What does [...arr] create?






Q5. Spread operator was introduced in ______.