Spread Operator in JavaScript with Examples

Learn how the JavaScript spread operator works in function calls, arrays, and objects with practical examples.

Published

Updated

Read time 2 min read

Reviewed byDeepak Prasad

Spread Operator in JavaScript with Examples

The spread operator in JavaScript is written as ... and expands an iterable or object into individual values. It is useful in function calls, array literals, and object literals.

Spread syntax is one of the most practical ES6 features because it makes copying, merging, and passing values much easier to read. If you are building arrays from parts, JavaScript add arrays is the related topic.

Tested on: Node.js v20.18.2. A short note after each runnable snippet describes what you should see in the console.


Use spread in function calls

Spread expands array elements into separate function arguments.

javascript
function sum(a, b, c) {
  return a + b + c;
}

const numbers = [1, 2, 3];
console.log("spread-fn:", sum(...numbers));
Output

You should see one line logging spread-fn: 6.

Use this when a function expects individual arguments rather than an array.


Use spread in arrays

You can expand arrays into a new array literal.

javascript
const a = [1, 2, 3];
const b = [4, 5, 6];
console.log("spread-array:", [...a, ...b].join(","));
console.log("spread-copy:", [...a].join(","));
Output

You should see 2 lines, in order: spread-array: 1,2,3,4,5,6, spread-copy: 1,2,3.

This is the standard pattern for merging arrays or making a shallow copy.


Use spread in objects

Object spread copies enumerable properties into a new object.

javascript
const obj = { x: 1, y: 2 };
const merged = { ...obj, z: 3 };
console.log("spread-object:", JSON.stringify(merged));
Output

You should see one line logging spread-object: {"x":1,"y":2,"z":3}.

Use this when you need a new object with a few additional fields.


Summary

The JavaScript spread operator expands arrays, objects, and iterable values into individual elements or properties. Use it for function calls, array merging, object copying, and cleaner ES6 code. The syntax is short, but it solves a lot of everyday data-shaping problems.


Official documentation

Olorunfemi Akinlua

Boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs …