es6

Chapter 8: Spread Operator in JavaScript (ES6) with Real-World Examples

Chapter 8: Spread Operator in JavaScript (ES6)

The spread operator (...) is one of the most powerful features introduced in ES6. It allows you to unpack or “spread” elements from arrays, strings, or objects into individual elements. This leads to cleaner, more readable code — especially when copying, merging, or manipulating arrays and objects.

🔓 Basic Usage – Expanding Arrays


let fullName = ['Umar', 'Rahman'];

console.log(fullName);       // ['Umar', 'Rahman']
console.log(...fullName);    // Umar Rahman
  

In the second line, the array is “spread” — each item is printed separately instead of as an array.

🔤 Spread on Strings – Expanding Characters


let language = "JavaScript";
let letters = [...language];

console.log(letters);
// ['J', 'a', 'v', 'a', 'S', 'c', 'r', 'i', 'p', 't']
  

Spread breaks a string into individual characters and stores them in an array.

🔗 Merging Arrays (ES5 vs ES6)

Before ES6 (using concat):


var array1 = ["Rahul", "Roy"];
var array2 = ["Neeraj", "Pandit"];

var result = array1.concat(array2);
console.log(result);
  

With ES6 Spread:


var array1 = ["Rahul", "Roy"];
var array2 = ["Neeraj", "Pandit"];

var result = [...array1, ...array2];
console.log(result);
// ['Rahul', 'Roy', 'Neeraj', 'Pandit']
  

➕ Adding One Array into Another with push()


let arr1 = ['Rajesh', 'Karim', 'Rahul'];
let arr2 = ['Seema', 'Neha', 'Aamar'];

arr1.push(...arr2);
console.log(arr1);
// ['Rajesh', 'Karim', 'Rahul', 'Seema', 'Neha', 'Aamar']
  

📋 Copying Arrays


const original = ['one', 'two'];
const copy = [...original, 'three', 'four'];

console.log(copy);
// ['one', 'two', 'three', 'four']
  

🧱 Copying & Merging Objects


let o1 = { a: 1, b: 2 };
let o2 = { c: 3, d: 4, ...o1 };

console.log(o2);
// { c: 3, d: 4, a: 1, b: 2 }
  

Use Case: Add new values to existing API data or merge user input with defaults.

🧪 Real-Time Form Example with Spread Operator

This example collects user data from a form and creates an object using the spread operator pattern.


document.getElementById('userForm').addEventListener('submit', function(event) {
  event.preventDefault();

  const formElements = [...event.target.elements];
  const formData = {};

  formElements.forEach(element => {
    if (element.name) {
      formData[element.name] = element.value;
    }
  });

  document.getElementById('submittedData').textContent = JSON.stringify(formData, null, 2);
});
  

🆚 Spread Operator vs Rest Parameter

  • Spread: Breaks data into individual elements — used in function calls, arrays, objects.
  • Rest: Gathers multiple values into a single parameter — used in function definitions.

📘 Assignments: Practice Spread Operators

  1. Use the spread operator to clone the array ['apple', 'banana'] and add two more fruits to it.
  2. Merge two objects: {name: 'Raj'} and {age: 30, country: 'India'} using spread syntax.
  3. Break the string "Spread" into an array of characters using spread.
  4. Create a form with 3 fields (name, email, message). Use the spread operator to collect values into an object.
  5. Push all elements of one array into another using push(...array2) and log the result.

📌 Summary

  • ... spread operator is used to expand arrays, strings, and objects.
  • It simplifies combining and copying arrays/objects.
  • It enhances readability and reduces need for concat() or Object.assign().
  • It’s essential for modern JavaScript use cases like API responses, forms, and data processing.

Leave a Reply

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