LearnFrenzy
Sign in Take a free test
JS

JavaScript Programming · Topic 17 of 25

Spread and Rest Operators Questions and Concepts

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Spread and Rest Operators · Study material

The three dots ... do two opposite jobs in JavaScript. Spread expands a collection into individual elements – [...a, ...b], Math.max(...nums), { ...defaults, ...options }. Rest collects individual elements into a collection – function log(...messages), const [first, ...others] = list, const { password, ...safe } = user. Together they power immutable updates in React and Redux, flexible function signatures and clean merges. Interviews test the details: copies are shallow, later properties win (even undefined), null can be spread into objects but not into arrays, and rest must be last. Then test yourself with 60 practice questions – 15 MCQs, 20 predict-the-output puzzles, 15 debugging questions and 10 coding problems – every one run on Node.js.

Spread or rest? Look at the position

Where the ... appearsRoleExample
Inside an array literalspread[...a, 4]
In a function callspreadfn(...args)
Inside an object literalspread{ ...obj, x: 1 }
In a parameter listrestfunction f(a, ...rest)
In a destructuring patternrestconst [x, ...rest] = arr

Spreading arrays

Spread inside an array literal copies the items of any iterable into the new array: copy an array, merge several, or insert items at any position. The result is a new array, but a shallow one – objects inside are shared.

const base = ["html", "css"];
const copy = [...base];                              // a new array with the same items
const full = [...base, "js", ...["react", "node"]];  // merge and insert anywhere
const withFirst = ["git", ...base];
copy.push("sass");                                   // the copy is independent of base
console.log(base, full.length, withFirst);

Output

[ 'html', 'css' ] 5 [ 'git', 'html', 'css' ]

Spreading into function calls and other iterables

fn(...arr) passes the items as separate arguments – the modern replacement for fn.apply(null, arr). Strings, Sets, Maps and generators can all be spread. Plain objects cannot be spread into arrays or calls, because they are not iterable.

const marks = [72, 95, 61];
console.log(Math.max(...marks), Math.min(...marks, 50));    // array → separate arguments
// Any iterable can be spread into an array
console.log([..."hey"], [...new Set([1, 1, 2])], [...new Map([["a", 1]])]);
const date = new Date(Date.UTC(...[2026, 10, 30]));
console.log(date.toISOString().slice(0, 10));

Output

95 50
[ 'h', 'e', 'y' ] [ 1, 2 ] [ [ 'a', 1 ] ]
2026-11-30

Spreading objects

Object spread (ES2018) copies properties into a new object literal, in order, so later properties overwrite earlier ones – including with undefined. ...(condition && { key: value }) adds properties only when the condition is true, because spreading false, null or undefined adds nothing.

const defaults = { theme: "light", lang: "en", fontSize: 14 };
const user = { lang: "hi", fontSize: undefined };
const settings = { ...defaults, ...user };           // later properties win – even an undefined value!

const isAdmin = true;
const profile = {
  name: "Asha",
  ...(isAdmin && { role: "admin" }),                 // conditional spread: adds role only when true
  ...(false && { debug: true }),                     // spreading false adds nothing
};
console.log(settings);
console.log(profile);

Output

{ theme: 'light', lang: 'hi', fontSize: undefined }
{ name: 'Asha', role: 'admin' }

Rest parameters

A rest parameter collects the remaining arguments into a real array – unlike the old arguments object, which is array-like, includes every argument and does not exist in arrow functions. There can be only one rest parameter and it must be last.

// Rest parameter: the remaining arguments as a real array (must be last)
function logAll(level, ...messages) {
  return `[${level}] ${messages.join(" | ") || "-"} (${messages.length})`;
}
console.log(logAll("INFO", "server started", "port 3000"));
console.log(logAll("WARN"));

const sumAll = (...nums) => nums.reduce((a, b) => a + b, 0);   // arrow functions have no arguments: use rest
console.log(sumAll(...[1, 2], 3, ...new Set([4])));             // spread and rest together

Output

[INFO] server started | port 3000 (2)
[WARN] - (0)
10

Rest in destructuring

In an array pattern, rest collects the remaining items; in an object pattern, it collects the remaining own enumerable properties – the standard way to remove fields from an object without changing it.

const [winner, runnerUp, ...others] = ["Asha", "Ravi", "Meera", "Kiran"];
const { password, ...publicData } = { id: 1, name: "Dev", password: "x" };   // omit a field
console.log(winner, others, publicData);

Output

Asha [ 'Meera', 'Kiran' ] { id: 1, name: 'Dev' }

Immutable updates

Because spread copies only one level, updating nested state immutably means spreading every level on the path to the change and reusing everything else. React and Redux rely on this: a changed object is a new object, so a simple !== check detects the change.

const state = { user: { name: "Asha", tags: ["js"] }, theme: "dark" };
// Copy every level that changes; reuse the levels that do not
const next = {
  ...state,
  user: { ...state.user, tags: [...state.user.tags, "react"] },
};
console.log(state.user.tags, next.user.tags, state.theme === next.theme, state.user === next.user);

Output

[ 'js' ] [ 'js', 'react' ] true false

What object spread copies

Object spread copies own, enumerable properties (string and symbol keys). It skips inherited and non-enumerable properties, calls getters once and copies the resulting value, and ignores null and undefined. Spreading a string copies its characters as indexed properties.

// Object spread copies OWN, ENUMERABLE properties; getters are run once and their value copied
const proto = { inherited: true };
const source = Object.create(proto, {
  visible: { value: 1, enumerable: true },
  hidden: { value: 2, enumerable: false },
});
let reads = 0;
const withGetter = { get now() { reads++; return "value"; } };
const copy = { ...source, ...withGetter, ...null, ...undefined, ..."hi" };   // null/undefined add nothing
console.log(copy, reads);

Output

{ '0': 'h', '1': 'i', visible: 1, now: 'value' } 1

Common mistakes

  • Assuming spread copies deeply – nested objects and arrays are shared.
  • Putting defaults last – { ...user, ...defaults } overwrites the user's choices.
  • Spreading an object that has undefined values – undefined overwrites the default.
  • [...null] or fn(...undefined) – TypeError; object spread tolerates them, array spread does not.
  • new Set(...arr) – passes only the first item; write new Set(arr).
  • Spreading a string where an array was meant – [...tags, ..."react"] adds five letters.
  • Spreading huge arrays into a call – RangeError; use reduce or a loop.

Key points to remember

  • Spread expands; rest collects – the position tells you which.
  • Array spread and call spread need iterables; object spread takes any object (and ignores null/undefined).
  • Object spread: later wins, own enumerable only, getters called once.
  • All spread copies are shallow.
  • Rest parameters are real arrays, must be last, and replace arguments.
  • Object rest removes fields without mutating the source.
  • Immutable nested updates spread each level on the path.

Frequently asked questions

Spread or Object.assign?

Spread for creating new objects (the common case). Object.assign when you deliberately want to modify an existing target – it runs the target's setters, while spread defines plain properties.

How do I deep-copy instead?

structuredClone(value), or spread every level you need to change (the immutable-update pattern) so unchanged parts are shared on purpose.

Is spreading slow?

It copies every element or property, so spreading large collections inside loops costs O(n) each time. For one-off copies and merges it is perfectly fine.

Where can I learn more?

Read Destructuring and Spread and JavaScript Functions in the JavaScript tutorial, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About JavaScript Programming

Why it matters

  • JavaScript runs every web page and, with Node.js, servers, tools and APIs – it is the most used language in the world
  • Front-end, full-stack and MERN roles test JavaScript first, and many campus coding rounds allow it
  • "Predict the output" questions on hoisting, closures, this, coercion and the event loop are interview favourites
  • Modern ES6+ – let/const, arrow functions, destructuring, promises and async/await – is what companies expect from freshers

Who it is for

  • College students (B.Tech, BCA, MCA, B.Sc CS) learning web development and preparing for semester exams and viva
  • Freshers preparing for campus placements, online assessments and front-end interviews
  • Developers moving to React, Angular, Vue or Node.js who need strong core JavaScript
  • Anyone revising ES6 and asynchronous JavaScript before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs on concepts and ES6 features
  • "Predict the output" puzzles – hoisting, coercion, closures, promises and timers
  • "Find the error" debugging: SyntaxError, ReferenceError, TypeError and silent logic bugs
  • Coding problems with solutions and real output, every one run on Node.js – run any study example in your browser

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture, Cognizant tests
  • Front-end developer interviews
  • MERN / full-stack interviews
  • Online coding assessments
  • University practicals

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, debugging, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links