OnlineCBT Logo OnlineCBT
JavaScript Tutorial
JAVASCRIPT · LESSON 16

Spread and Rest Operators (...)

By Ratan Updated: 16 Oct 2026

Copy, merge, and expand arrays and objects using the ES6 spread syntax (...).

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

The same three dots serve two directions

Spread expands values into a call, array or object literal. Rest collects remaining values into a parameter or destructuring target. Read the dots in context instead of treating them as one universal deep-copy operator.

const basics = ['Variables', 'Loops'];
const syllabus = [...basics, 'Functions'];
console.log(syllabus); // ['Variables', 'Loops', 'Functions']

const defaults = { theme: 'light', pageSize: 10 };
const preferences = { ...defaults, pageSize: 20 };
console.log(preferences.pageSize); // 20

function total(...numbers) {
  return numbers.reduce((sum, value) => sum + value, 0);
}
console.log(total(2, 3, 4)); // 9

Order controls overwrites

Later object properties replace earlier properties with the same key. Reversing the order of defaults and preferences can overwrite a user's intended choice. Build explicit objects at trust boundaries rather than spreading arbitrary request fields into sensitive records.

Copies are shallow

const original = { address: { city: 'Dausa' } };
const copy = { ...original };
copy.address.city = 'Jaipur';
console.log(original.address.city); // Jaipur

const separate = { ...original, address: { ...original.address } };
separate.address.city = 'Ajmer';
console.log(original.address.city); // Jaipur

The first copy still shares the nested address. The second explicitly copies that nested object. For more complex data, choose a cloning or immutable-update strategy that matches its actual types; JSON stringify/parse is not a universal clone.

Spread into calls

Math.max(...[4, 9, 2]) produces 9. Very large argument lists can exceed runtime limits, so do not spread an unbounded dataset into a function call. Array spread needs an iterable; object spread copies own enumerable properties and follows different rules.

Practice

  1. Merge two lesson arrays while preserving both originals.
  2. Override a default theme and explain why property order matters.
  3. Collect the first item and remaining items with array destructuring rest.
  4. Update a nested student score without mutating the original nested object.

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
Address Contact

+91 7877547686

E-mail

onlinecbtportal@gmail.com

Helpline Number

+91 7877547686


Click To Download
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat