Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Spread Operator

Master the spread operator. Learn to spread arrays, objects, and function arguments.

Why this matters

The spread operator is essential for modern JavaScript. It simplifies array and object operations, makes code more readable, and enables functional programming patterns.

What is the Spread Operator?

The spread operator (...) allows an iterable (array, string, etc.) to be expanded in places where zero or more elements are expected. It's the opposite of rest parameters.

Spread operators are useful for copying arrays, merging arrays, passing arguments, and spreading object properties.

Basic Spread Operator

// Spreading an array into function arguments
const numbers = [1, 2, 3];
console.log(Math.max(...numbers)); // Same as Math.max(1, 2, 3)
// Output: 3

// Copying arrays
const arr1 = [1, 2, 3];
const arr2 = [...arr1]; // Creates a new array
console.log(arr2); // [1, 2, 3]

// Merging arrays
const arr3 = [1, 2];
const arr4 = [3, 4];
const merged = [...arr3, ...arr4];
console.log(merged); // [1, 2, 3, 4]

// Spreading strings
const str = "hello";
const chars = [...str];
console.log(chars); // ['h', 'e', 'l', 'l', 'o']

Spread operator expands iterables into individual elements.

Spread Operator with Arrays

The spread operator is powerful for array operations like copying, merging, and adding elements.

Array Operations with Spread

// Copying arrays (shallow copy)
const original = [1, 2, 3];
const copy = [...original];
copy[0] = 99;
console.log(original[0]); // 1 (not affected)

// Merging arrays
const arr1 = [1, 2];
const arr2 = [3, 4];
const arr3 = [5, 6];
const merged = [...arr1, ...arr2, ...arr3];
console.log(merged); // [1, 2, 3, 4, 5, 6]

// Adding elements to arrays
const baseArray = [2, 3];
const newArray = [1, ...baseArray, 4];
console.log(newArray); // [1, 2, 3, 4]

// Creating array with duplicates removed (using Set)
const arr = [1, 2, 2, 3, 3, 3];
const unique = [...new Set(arr)];
console.log(unique); // [1, 2, 3]

// Reversing arrays without mutating
const original2 = [1, 2, 3];
const reversed = [...original2].reverse();
console.log(original2); // [1, 2, 3] (unchanged)
console.log(reversed); // [3, 2, 1]

Spread operator enables non-destructive array operations.

Spread Operator with Objects

The spread operator can also spread object properties, useful for copying and merging objects.

Object Operations with Spread

// Copying objects (shallow copy)
const original = { a: 1, b: 2, c: 3 };
const copy = { ...original };
copy.a = 99;
console.log(original.a); // 1 (not affected)

// Merging objects
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const merged = { ...obj1, ...obj2 };
console.log(merged); // { a: 1, b: 2, c: 3, d: 4 }

// Overriding properties
const defaults = { color: "blue", size: "large" };
const userOptions = { color: "red" };
const final = { ...defaults, ...userOptions };
console.log(final); // { color: "red", size: "large" }

// Adding new properties
const person = { name: "Alice", age: 25 };
const updated = { ...person, city: "NYC", age: 26 };
console.log(updated);
// { name: "Alice", age: 26, city: "NYC" }

Spread operator simplifies object manipulation and merging.

Spread in Function Calls

Use the spread operator to pass array elements as individual arguments to functions.

Function Arguments with Spread

// Spreading array as function arguments
function sum(a, b, c) {
  return a + b + c;
}

const numbers = [1, 2, 3];
console.log(sum(...numbers)); // 6 (same as sum(1, 2, 3))

// Applying Math functions
console.log(Math.min(...[5, 2, 8, 1])); // 1
console.log(Math.max(...[5, 2, 8, 1])); // 8

// Spreading in method calls
const arr = [1, 2, 3];
arr.push(...[4, 5, 6]);
console.log(arr); // [1, 2, 3, 4, 5, 6]

// Practical example: logger
function log(level, ...messages) {
  console.log("[" + level + "]", ...messages);
}

const prefix = "[INFO]";
const data = ["User logged in", { id: 123 }];
log("INFO", ...data);
// [INFO] User logged in { id: 123 }

Spread operator converts arrays into function arguments seamlessly.

Spread vs Rest Parameters

While spread and rest both use '...', they work in opposite directions. Spread expands arrays, rest collects arguments.

Spread vs Rest

// REST - collects arguments into array
function sum(...numbers) {
  return numbers.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3)); // 6

// SPREAD - expands array into arguments
const arr = [1, 2, 3];
console.log(sum(...arr)); // 6

// REST in function definition (gathers)
function concat(...strings) {
  return strings.join(" ");
}

// SPREAD in function call (spreads)
const words = ["hello", "world"];
console.log(concat(...words)); // "hello world"

// Both can be used together
function combine(first, ...rest) {
  return [first, ...rest];
}
const input = [2, 3, 4];
const result = combine(1, ...input);
console.log(result); // [1, 2, 3, 4]

Rest collects items into arrays, spread expands arrays into items.

Common Mistakes

  • Confusing spread with rest: Rest parameters (...args) collect arguments in function definitions. Spread operator (...array) expands arrays in calls.
  • Using spread with non-iterable objects: Spread only works with iterables (arrays, strings, Sets, Maps). For objects, use { ...obj }.
  • Not realizing shallow copy limitations: Spread operator creates shallow copies. Nested objects/arrays are still referenced, not deeply cloned.

FAQ

What is the spread operator?

The spread operator (...) expands iterables (arrays, strings, etc.) into individual elements. It's useful for copying, merging, and spreading values.

What's the difference between spread and rest?

Rest parameters (...args) collect multiple values into an array in function definitions. Spread operator expands an array into individual elements in function calls or literals.

Does spread make a deep copy?

No, spread makes a shallow copy. If the array/object contains nested structures, those nested items are still referenced, not cloned.

Can I use spread with objects?

Yes, you can spread object properties: { ...obj }. This creates a new object with copied properties.