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

Coding Techniques

Spread and Rest Operators · Study material

Spread vs Object.assign

Both copy own enumerable properties, but Object.assign assigns into an existing target (running its setters and mutating it), while spread defines properties on a brand-new object:

// Object.assign WRITES into its target (running setters); spread always creates a fresh object
const target = {
  set price(v) { this._price = Math.round(v); },
};
Object.assign(target, { price: 99.6 });
const spreadCopy = { ...target, price: 99.6 };

console.log(target._price, Object.keys(target));
console.log(spreadCopy.price, Object.keys(spreadCopy));

Output

100 [ 'price', '_price' ]
99.6 [ 'price', '_price' ]

Immutable array operations

Insert, remove, replace and toggle without mutating the original – the patterns behind every React list update:

const list = ["a", "b", "c", "d"];
const insertAt = (arr, i, item) => [...arr.slice(0, i), item, ...arr.slice(i)];
const removeAt = (arr, i) => [...arr.slice(0, i), ...arr.slice(i + 1)];
const replaceAt = (arr, i, item) => arr.map((x, j) => (j === i ? item : x));
const toggle = (arr, item) => (arr.includes(item) ? arr.filter((x) => x !== item) : [...arr, item]);

console.log(insertAt(list, 2, "X"), removeAt(list, 1));
console.log(replaceAt(list, 0, "Z"), toggle(list, "c"), toggle(list, "e"));
console.log(list);                       // never changed

Output

[ 'a', 'b', 'X', 'c', 'd' ] [ 'a', 'c', 'd' ]
[ 'Z', 'b', 'c', 'd' ] [ 'a', 'b', 'd' ] [ 'a', 'b', 'c', 'd', 'e' ]
[ 'a', 'b', 'c', 'd' ]

Spread and rest at a glance

GoalCode
Copy an array / object[...arr] / { ...obj }
Merge with overrides{ ...defaults, ...options }
Add a property only if{ ...(ok && { k: v }) }
Array as argumentsMath.max(...nums)
Unique values[...new Set(arr)]
Any number of argumentsfunction f(...args)
Remove a fieldconst { pw, ...safe } = user
Update nested state{ ...s, user: { ...s.user, name } }

Spread and rest checklist

  • Put defaults first and overrides last when merging.
  • Strip undefined values before merging if they should not override defaults.
  • Spread every changed level in nested updates.
  • Guard optional arrays before spreading: [...(list ?? [])].
  • Use rest parameters instead of arguments.
  • Do not spread very large arrays into function calls.

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