Everything, Everywhere
Verified Specification | Standardized Formulas | Instant Precision
Secure & Private (Zero Data Retention) Free Access • No Sign-Up

Spread & Rest Operators

The three dots (...) act as either a spread operator or rest parameters depending on the context.

Try It Yourself

      
📋 Copy Spread & Rest Operator Patterns Snippet
// Rest Parameters in Function Signatures
function logMessage(level, ...details) {
  console.log(`[${level}]`, details.join(" "));
}

// Spread in Object & Array Merging
const base = { active: true, theme: "dark" };
const userConfig = { theme: "light" };
const merged = { ...base, ...userConfig }; // theme becomes 'light'

⚠️ 5 Fatal Traps & JavaScript Pitfalls

Trap #1: Spread Operator Creates Strictly Shallow Copies
Spreading an array or object (const copy = [...items]) only duplicates top-level primitives. Nested objects share the exact same memory references.
Trap #2: Call Stack Exceeded on Massive Array Spread
Passing Math.max(...giantArray) with 100,000+ items overflows JavaScript's maximum function call stack limit, throwing RangeError: Maximum call stack size exceeded. Use reduce().
Trap #3: Rest Parameter Must Be the Final Parameter
Writing function f(...rest, last) is a syntax error. Rest parameters must always be positioned at the very end of parameter lists.
Trap #4: Object Spread Precedence Overwriting Defaults
Writing { ...userOverrides, ...defaultSettings } allows default settings to overwrite user customizations! Always put defaults first.
Trap #5: Spreading Non-Iterables into Arrays
Writing [...123] or [...null] throws TypeError: ... is not iterable.

💬 Frequently Asked Questions

What is the visual and functional difference between spread and rest?
Both use ... syntax. Spread expands an iterable into individual elements or object properties. Rest condenses multiple individual elements into a single array or object.
Why does spreading an object into an array fail?
Standard objects do not implement the Iterable protocol ([Symbol.iterator]), so spreading an object into [...] throws a TypeError.
How does object spread handle non-enumerable properties?
Object spread ({ ...obj }) only copies own enumerable properties, ignoring non-enumerable properties and prototype methods.
Can you use the spread operator to convert a NodeList to an Array?
Yes: const elements = [...document.querySelectorAll(".item")]; converts a NodeList into a standard Array.
How does spread perform compared to Object.assign()?
Both perform shallow property copying. Spread syntax is slightly more concise and does not trigger setters on the target object.
Sponsored Utility
While You're Here
Sponsored Recommendations
Advertisement