惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
Tailwind CSS Blog
J
Java Code Geeks
Microsoft Azure Blog
Microsoft Azure Blog
GbyAI
GbyAI
爱范儿
爱范儿
量子位
Martin Fowler
Martin Fowler
V
V2EX
博客园 - 三生石上(FineUI控件)
I
InfoQ
MongoDB | Blog
MongoDB | Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
N
Netflix TechBlog - Medium
D
DataBreaches.Net
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Last Week in AI
Last Week in AI
U
Unit 42
Apple Machine Learning Research
Apple Machine Learning Research
H
Help Net Security
T
The Blog of Author Tim Ferriss
Hugging Face - Blog
Hugging Face - Blog
美团技术团队
Engineering at Meta
Engineering at Meta

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Spread vs Rest Operators in JavaScript: Expand or Collect...
Ritam Saha · 2026-04-25 · via DEV Community

Introduction

Imagine you're juggling arrays and objects in JavaScript, and suddenly you need to copy, merge, or slice them without breaking a sweat.
Entry of the spread operator (...) and rest operator (...)—two syntactic superheroes that look identical buthave different jobs. They're game-changers for clean, readable code in modern JS and provide perfect Developer's experience, especially in React apps, Node.js backend applications.
But what's the difference between these two?

Spread expands values into individual elements;
Rest collects them into a single array or object

Let's dive in with examples and see how they shine (or clash) in real scenarios.


What the Spread Operator Does: Expanding Values

The spread operator (...) is like dropping a glass from a height and it spreads down completely with so many broken parts; this takes an iterable—like an array or object—and spreads (expands) its elements into individual items. It's like unpacking a box: everything spills out for easy use.

const fruits = ['apple', 'banana'];
const moreFruits = ['orange', ...fruits, 'grape'];
// Result: ['orange', 'apple', 'banana', 'grape']

Enter fullscreen mode Exit fullscreen mode

Here, ...fruits expands the array, letting you merge without messy loops.

const user = { name: 'Ritam', city: 'Kolkata' };
const updatedUser = { ...user, age: 20, hobby: 'coding' };
// Result: { name: 'Ritam', city: 'Kolkata', age: 20, hobby: 'coding' }

Enter fullscreen mode Exit fullscreen mode

Spread creates shallow copies and merges—perfect for immutable updates in state management.

spread operator


What the Rest Operator Does: Collecting Values

The rest operator (...) does the opposite: it gathers (collects) elements into a single array. It only works in function parameters depending on the passed arguments and for destrcturing, acting like a "vacuum" for leftovers.

function sum(...numbers) {
  return numbers.reduce((acc, num) => acc + num, 0);
}
sum(1, 2, 3, 4); // Result: 10 (numbers = [1, 2, 3, 4])

Enter fullscreen mode Exit fullscreen mode

Rest collects all arguments into numbers.

const [first, ...rest] = ['apple', 'banana', 'orange']; //Array destructuring
console.log(first); // 'apple'
console.log(rest);  // ['banana', 'orange']

Enter fullscreen mode Exit fullscreen mode

It grabs the first item, then collects the rest.

rest operator


Key Differences: Spread Expands, Rest Collects

Aspect Spread (...) Rest (...)
Direction Expands (unpacks) Collects (packs)
Context Anywhere (arrays, objects, calls) Function params or destructuring
Use Case Copying, merging, passing args Variable args, destructuring leftovers
Example [...arr] clones array function(...args)

Spread is for spreading values outward; rest is for gathering them inward. Confuse them? Your code breaks—spread won't work in params!


Practical Use Cases: Real-World Wins

Cloning Arrays/Objects (Spread): Avoid mutations in React state.

   const state = { users: [] };
   const newState = { ...state, users: [...state.users, newUser] };

Enter fullscreen mode Exit fullscreen mode

Function Arguments (Spread): Pass arrays dynamically.

   const coords = [10, 20];
   console.log(Math.max(...coords)); // 20

Enter fullscreen mode Exit fullscreen mode

API Data Merging (Spread): Combine defaults with user input.

   const defaults = { method: 'GET' };
   const config = { ...defaults, url: '/api/users' };
   fetch(config.url, config);

Enter fullscreen mode Exit fullscreen mode

Variable Args in Node.js Utils (Rest): Build flexible helpers.

   function log(...messages) {
     console.log(new Date(), ...messages);
   }
   log('User login:', userId, timestamp);

Enter fullscreen mode Exit fullscreen mode

Destructuring Props (Rest): In React components.

   function Button({ children, ...props }) {
     return <button {...props}>{children}</button>;
   }

Enter fullscreen mode Exit fullscreen mode

These patterns pop up everywhere—from your full-stack deploys on Vercel to interview coding rounds.


Wrapping Up: Master Both for Cleaner JS

Spread and rest operators turn clunky array/object ops into elegant one-liners, saving you headaches in full-stack dev. Remember: spread expands for copying/merging; rest collects for flexible params. Practice with small examples, and they'll become second nature for your portfolio projects. Next time you're refactoring Node.js routes or React components, reach for ...—your future self will thank you. What's your favorite use case? Drop it in the comments!