How TO - The Spread Operator (...)

Learn how to use the three dots operator (...) a.k.a the spread operator in JavaScript.

The Spread Operator

The JavaScript spread operator ( ... ) expands an iterable (like an array) into more elements.

This allows us to quickly copy all or parts of an existing array into another array:

Assign the first and second items from numbers to variables and put the rest in an array:

The spread operator is often used to extract only what's needed from an array:

We can use the spread operator with objects too:

Notice the properties that did not match were combined, but the property that did match, color , was overwritten by the last object that was passed, updateMyVehicle . The resulting color is now yellow.

See also : JavaScript ES6 Tutorial .

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Home » JavaScript Array Methods » JavaScript Spread Operator

JavaScript Spread Operator

Summary : in this tutorial, you will learn about the JavaScript spread operator that spreads out elements of an iterable object.

Introduction to the JavaScript spread operator

ES6 provides a new operator called spread operator that consists of three dots (...) . The spread operator allows you to spread out elements of an iterable object such as an array , map , or set . For example:

In this example, the three dots ( ... ) located in front of the odd array is the spread operator. The spread operator ( ... ) unpacks the elements of the odd array.

Note that ES6 also has the three dots ( ... ) which is a rest parameter that collects all remaining arguments of a function into an array.

In this example, the rest parameter ( ... ) collects the arguments 3, 4, and 5 into an array args . So the three dots ( ... ) represent both the spread operator and the rest parameter.

Here are the main differences:

  • The spread operator ( ... ) unpacks the elements of an iterable object.
  • The rest parameter ( ... ) packs the elements into an array.

The rest parameters must be the last arguments of a function . However, the spread operator can be anywhere:

Note that ES2018 expands the spread operator to objects, which is known as object spread .

Let’s look at some scenarios where you can use the spread operators.

JavaScript spread operator and apply() method

See the following compare() function that compares two numbers:

In ES5, to pass an array of two numbers to the compare() function, you often use the apply() method as follows:

However, by using the spread operator, you can pass an array of two numbers to the compare() function:

The spread operator spreads out the elements of the array so a is 1 and b is 2 in this case.

A better way to use the Array’s push() method example

Sometimes, a function may accept an indefinite number of arguments. Filling arguments from an array is not convenient.

For example, the push() method of an array object allows you to add one or more elements to an array. If you want to pass an array to the push() method, you need to use apply() method as follows:

This solution looks verbose.

The following example uses the spread operator to improve the readability of the code:

As you can see, using the spread operator is much cleaner.

JavaScript spread operator and array manipulation

1) constructing array literal.

The spread operator allows you to insert another array into the initialized array when you construct an array using the literal form. See the following example:

2) Concatenating arrays

Also, you can use the spread operator to concatenate two or more arrays:

3) Copying an array

In addition, you can copy an array instance by using the spread operator:

Note that the spread operator only copies the array itself to the new one, not the elements. This means that the copy is shallow, not deep.

JavaScript spread operator and strings

Consider the following example:

In this example, we constructed the chars array from individual strings. When we applied the spread operator to the ‘BC’string, it spread out each character of the string 'BC' into individual characters.

  • The spread operator is denoted by three dots ( ... ).
  • The spread operator unpacks elements of iterable objects such as arrays, sets, and maps into a list.
  • The rest parameter is also denoted by three dots ( ... ). However, it packs the remaining arguments of a function into an array.
  • The spread operator can be used to clone an iterable object or merge iterable objects into one.

JavaScript Destructuring and the Spread Operator – Explained with Example Code

Nishant Kumar

JavaScript has two awesome data structures that help you write clean and efficient code. But handling them can get messy sometimes.

In this blog, I am going to show you how to handle destructuring in arrays and objects in JavaScript. We'll also learn how to use the spread operator as well.

Let's dive in.

What is Array Destructuring in JavaScript?

Let's say we have an array that contains five numbers, like this:

To get the elements from the array, we can do something like getting the number according to its indexes:

But this method is old and clunky, and there is a better way to do it – using array destructuring. It looks like this:

Both methods above will yield the same result:

Screenshot-2021-08-07-105209

Now, we have five elements in the array, and we print those.  But what if we want to skip one element in between?

Here, we have skipped indexThird , and there's an empty space between indexTwo and indexFour.

Screenshot-2021-08-07-105709

You can see that we are not getting the third element because we have set it as empty.

What is Object Destructuring in JavaScript?

This destructuring works well with objects too. Let me give you an example.

Let's say we want the name, salary, and weight from this object to be printed out in the console.

We can get them using the keys, which are name, salary, and weight.

But this code becomes difficult to understand sometimes. That's when destructuring comes in handy:

And now, we can just log name, salary, and weight instead of using that old method.

Screenshot-2021-08-07-111356

We can also use destructuring to set default values if the value is not present in the object.

Here, we have name and weight present in the object, but not the salary:

Screenshot-2021-08-07-111659

We will get an undefined value for the salary.

To correct that issue, we can set default values when we are destructuring the object.

Screenshot-2021-08-07-111907

You can see that we get 200 as the Salary. This only works when we don't have that key in the object, and we want to set a default value.

Add salary in the object, and you will get 300 as the salary.

Screenshot-2021-08-07-112128

How to Use Object Destructuring with Functions

Let's say we have a function that prints all the data in the array to the console.

We are passing the object as a parameter in the function when it gets called:

Normally, we would do something like this – passing the object and logging it in the console.

Screenshot-2021-08-07-115047

But again, we can do the same using destructuring.

Here, we are destructuring the object into name, age, salary, height and weight in the function parameters and we print everything on the same line.

You can see how destructuring makes it so much easier to understand.

Screenshot-2021-08-07-115329

Let's look at one last example.

We have a function here which accepts two numbers. It returns an array adding them and multiplying them and logs them into the console.

Screenshot-2021-08-07-120108

Let's use destructuring here instead.

We can destructure it into addition and multiplication variables like this:

Screenshot-2021-08-07-120325

And in the output, you can see we get the addition and multiplication of both numbers.

What is the Spread Operator in JavaScript?

Spread means spreading or expanding. And the spread operator in JavaScript is denoted by three dots.

This spread operator has many different uses. Let's see them one by one.

Spread Operator Examples

Let's say we have two arrays and we want to merge them.

Screenshot-2021-08-07-112601

We are getting the combination of both arrays, which are array1 and array2.

But there is an easier way to do this:

In this case, we are using the spread operator to merge both arrays.

Screenshot-2021-08-07-113020

And you can see, we will get the same output.

Let's imagine another use case where we have to insert array1 between the elements of array2 .

For example, we want to insert array2 between the second and third element of array1 .

So, how do we do that? We can do something like this:

Screenshot-2021-08-07-113502

And you can see, we get the array1 elements between 7 and 8.

Now, let's merge two objects together using the spread operator.

We have two objects here. One contains firstName, age, and salary. The second one contains lastName, height, and weight.

Let's merge them together.

We have now merged both objects using the spread operator, and we've logged the value in the console.

Screenshot-2021-08-07-114101

You can see that we are getting the combination of both objects.

Lastly, we can also copy one array into another using the spread operator. Let me show you how it works:

Here, we are copying array1 into array2 using the spread operator.

Screenshot-2021-08-07-120757

We are logging array2 in the console, and we are getting the items of array1 .

That's all, folks! In this article, we learned about array and object destructuring and the spread operator.

You can also watch my Youtube video on Array and Object Destructuring and the Spread Operator if you want to supplement your learning.

Happy Learning.

I build projects to learn how code works. And while I am not coding, I enjoy writing poetry and stories, playing the piano, and cooking delicious meals.

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

  • Skip to main content
  • Select language
  • Skip to search
  • Spread syntax

Apply for new

A better way to concatenate arrays, spread with many values.

Spread syntax allows an iterable such as an array expression to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

For function calls:

For array literals:

For object literals (new in ECMAScript; stage 3 draft):

Spread in function calls

Replace apply.

It is common to use Function.prototype.apply in cases where you want to use the elements of an array as arguments to a function.

With spread syntax the above can be written as:

Any argument in the argument list can use spread syntax and it can be used multiple times.

When calling a constructor with new , it's not possible to directly use an array and  apply  ( apply does a [[Call]] and not a [[Construct]] ). However, an array can be easily used with new thanks to spread syntax:

To use new with an array of parameters without spread syntax, you would have to do it indirectly through partial application:

Spread in array literals

A more powerful array literal.

Without spread syntax, to create a new array using an existing array as one part of it, the array literal syntax is no longer sufficient and imperative code must be used instead using a combination of push , splice , concat , etc. With spread syntax this becomes much more succinct:

Just like spread for argument lists,  ... can be used anywhere in the array literal and it can be used multiple times.

Copy an array

Note: Spread syntax effectively goes one level deep while copying an array. Therefore, it may be unsuitable for copying multidimensional arrays as the following example shows (it's the same with Object.assign() and spread syntax).

Array.concat is often used to concatenate an array to the end of an existing array. Without spread syntax this is done as:

With spread syntax this becomes:

Array.unshift is often used to insert an array of values at the start of an existing array.  Without spread syntax this is done as:

With spread syntax this becomes:

Spread in object literals

The Rest/Spread Properties for ECMAScript proposal (stage 3) adds spread properties to object literals . It copies own enumerable properties from a provided object onto a new object.

Shallow-cloning (excluding prototype) or merging of objects is now possible using a shorter syntax than Object.assign() .

Note that Object.assign() triggers setters whereas spread syntax doesn't.

Only for iterables

Spread syntax (other than in the case of spread properties) can be applied only to iterable objects:

When using spread syntax for function calls, be aware of the possibility of exceeding the JavaScript engine's argument length limit. See  apply()  for more details.

Rest syntax (parameters)

Rest syntax looks exactly like spread syntax, but is used for destructuring arrays and objects. In a way, rest syntax is the opposite of spread syntax: spread 'expands' an array into its elements, while rest collects multiple elements and 'condenses' them into a single element. See rest parameters.

Specifications

Browser compatibility.

  • Rest parameters (also ‘ ... ’)

Document Tags and Contributors

  • ECMAScript 2015
  • JavaScript basics
  • JavaScript first steps
  • JavaScript building blocks
  • Introducing JavaScript objects
  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • Expressions and operators
  • Numbers and dates
  • Text formatting
  • Regular expressions
  • Indexed collections
  • Keyed collections
  • Working with objects
  • Details of the object model
  • Iterators and generators
  • Meta programming
  • A re-introduction to JavaScript
  • JavaScript data structures
  • Equality comparisons and sameness
  • Inheritance and the prototype chain
  • Strict mode
  • JavaScript typed arrays
  • Memory Management
  • Concurrency model and Event Loop
  • References:
  • ArrayBuffer
  • AsyncFunction
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • Intl.Collator
  • Intl.DateTimeFormat
  • Intl.NumberFormat
  • ParallelArray
  • ReferenceError
  • SIMD.Bool16x8
  • SIMD.Bool32x4
  • SIMD.Bool64x2
  • SIMD.Bool8x16
  • SIMD.Float32x4
  • SIMD.Float64x2
  • SIMD.Int16x8
  • SIMD.Int32x4
  • SIMD.Int8x16
  • SIMD.Uint16x8
  • SIMD.Uint32x4
  • SIMD.Uint8x16
  • SharedArrayBuffer
  • StopIteration
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • WebAssembly
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Arithmetic operators
  • Array comprehensions
  • Assignment operators
  • Bitwise operators
  • Comma operator
  • Comparison operators
  • Conditional (ternary) Operator
  • Destructuring assignment
  • Expression closures
  • Generator comprehensions
  • Grouping operator
  • Legacy generator function expression
  • Logical Operators
  • Object initializer
  • Operator precedence
  • Property accessors
  • async function expression
  • class expression
  • delete operator
  • function expression
  • function* expression
  • in operator
  • new operator
  • void operator
  • Legacy generator function
  • async function
  • for each...in
  • function declaration
  • try...catch
  • Arguments object
  • Arrow functions
  • Default parameters
  • Method definitions
  • Rest parameters
  • constructor
  • element loaded from a different domain for which you violated the same-origin policy.">Error: Permission denied to access property "x"
  • InternalError: too much recursion
  • RangeError: argument is not a valid code point
  • RangeError: invalid array length
  • RangeError: invalid date
  • RangeError: precision is out of range
  • RangeError: radix must be an integer
  • RangeError: repeat count must be less than infinity
  • RangeError: repeat count must be non-negative
  • ReferenceError: "x" is not defined
  • ReferenceError: assignment to undeclared variable "x"
  • ReferenceError: can't access lexical declaration`X' before initialization
  • ReferenceError: deprecated caller or arguments usage
  • ReferenceError: invalid assignment left-hand side
  • ReferenceError: reference to undefined property "x"
  • SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
  • SyntaxError: "use strict" not allowed in function with non-simple parameters
  • SyntaxError: "x" is a reserved identifier
  • SyntaxError: JSON.parse: bad parsing
  • SyntaxError: Malformed formal parameter
  • SyntaxError: Unexpected token
  • SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
  • SyntaxError: a declaration in the head of a for-of loop can't have an initializer
  • SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
  • SyntaxError: for-in loop head declarations may not have initializers
  • SyntaxError: function statement requires a name
  • SyntaxError: identifier starts immediately after numeric literal
  • SyntaxError: illegal character
  • SyntaxError: invalid regular expression flag "x"
  • SyntaxError: missing ) after argument list
  • SyntaxError: missing ) after condition
  • SyntaxError: missing : after property id
  • SyntaxError: missing ; before statement
  • SyntaxError: missing = in const declaration
  • SyntaxError: missing ] after element list
  • SyntaxError: missing formal parameter
  • SyntaxError: missing name after . operator
  • SyntaxError: missing variable name
  • SyntaxError: missing } after function body
  • SyntaxError: missing } after property list
  • SyntaxError: redeclaration of formal parameter "x"
  • SyntaxError: return not in function
  • SyntaxError: test for equality (==) mistyped as assignment (=)?
  • SyntaxError: unterminated string literal
  • TypeError: "x" has no properties
  • TypeError: "x" is (not) "y"
  • TypeError: "x" is not a constructor
  • TypeError: "x" is not a function
  • TypeError: "x" is not a non-null object
  • TypeError: "x" is read-only
  • TypeError: More arguments needed
  • TypeError: can't access dead object
  • TypeError: can't define property "x": "obj" is not extensible
  • TypeError: can't delete non-configurable array element
  • TypeError: can't redefine non-configurable property "x"
  • TypeError: cyclic object value
  • TypeError: invalid 'in' operand "x"
  • TypeError: invalid Array.prototype.sort argument
  • TypeError: invalid arguments
  • TypeError: invalid assignment to const "x"
  • TypeError: property "x" is non-configurable and can't be deleted
  • TypeError: setting getter-only property "x"
  • TypeError: variable "x" redeclares argument
  • URIError: malformed URI sequence
  • Warning: -file- is being assigned a //# sourceMappingURL, but already has one
  • Warning: 08/09 is not a legal ECMA-262 octal constant
  • Warning: Date.prototype.toLocaleFormat is deprecated
  • Warning: JavaScript 1.6's for-each-in loops are deprecated
  • Warning: String.x is deprecated; use String.prototype.x instead
  • Warning: expression closures are deprecated
  • Warning: unreachable code after return statement
  • JavaScript technologies overview
  • Lexical grammar
  • Enumerability and ownership of properties
  • Iteration protocols
  • Transitioning to strict mode
  • Template literals
  • Deprecated features
  • ECMAScript 2015 support in Mozilla
  • ECMAScript 5 support in Mozilla
  • ECMAScript Next support in Mozilla
  • Firefox JavaScript changelog
  • New in JavaScript 1.1
  • New in JavaScript 1.2
  • New in JavaScript 1.3
  • New in JavaScript 1.4
  • New in JavaScript 1.5
  • New in JavaScript 1.6
  • New in JavaScript 1.7
  • New in JavaScript 1.8
  • New in JavaScript 1.8.1
  • New in JavaScript 1.8.5
  • Documentation:
  • All pages index
  • Methods index
  • Properties index
  • Pages tagged "JavaScript"
  • JavaScript doc status
  • The MDN project

Popular Tutorials

Popular examples, reference materials, learn python interactively, js introduction.

  • Getting Started
  • JS Variables & Constants
  • JS console.log
  • JavaScript Data types
  • JavaScript Operators
  • JavaScript Comments
  • JS Type Conversions

JS Control Flow

  • JS Comparison Operators
  • JavaScript if else Statement
  • JavaScript for loop
  • JavaScript while loop
  • JavaScript break Statement
  • JavaScript continue Statement
  • JavaScript switch Statement

JS Functions

  • JavaScript Function
  • Variable Scope
  • JavaScript Hoisting
  • JavaScript Recursion
  • JavaScript Objects
  • JavaScript Methods & this
  • JavaScript Constructor
  • JavaScript Getter and Setter
  • JavaScript Prototype
  • JavaScript Array
  • JS Multidimensional Array
  • JavaScript String
  • JavaScript for...in loop
  • JavaScript Number
  • JavaScript Symbol

Exceptions and Modules

  • JavaScript try...catch...finally
  • JavaScript throw Statement
  • JavaScript Modules

JavaScript ES6

  • JavaScript Arrow Function
  • JavaScript Default Parameters
  • JavaScript Template Literals

JavaScript Spread Operator

  • JavaScript Map
  • JavaScript Set
  • Destructuring Assignment
  • JavaScript Classes
  • JavaScript Inheritance
  • JavaScript for...of
  • JavaScript Proxies

JavaScript Asynchronous

  • JavaScript setTimeout()
  • JavaScript CallBack Function
  • JavaScript Promise
  • Javascript async/await
  • JavaScript setInterval()

Miscellaneous

  • JavaScript JSON
  • JavaScript Date and Time
  • JavaScript Closure
  • JavaScript this
  • JavaScript use strict
  • Iterators and Iterables
  • JavaScript Generators
  • JavaScript Regular Expressions
  • JavaScript Browser Debugging
  • Uses of JavaScript

JavaScript Tutorials

JavaScript Destructuring Assignment

JavaScript typeof Operator

  • JavaScript Array reverse()
  • JavaScript Math max()
  • JavaScript Math min()

The spread operator is a new addition to the features available in the JavaScript ES6 version.

  • Spread Operator

The spread operator ... is used to expand or spread an iterable or an array . For example,

In this case, the code:

is equivalent to:

Copy Array Using Spread Operator

You can also use the spread syntax ... to copy the items into a single array. For example,

Clone Array Using Spread Operator

In JavaScript, objects are assigned by reference and not by values. For example,

Here, both variables arr1 and arr2 are referring to the same array. Hence the change in one variable results in the change in both variables.

However, if you want to copy arrays so that they do not refer to the same array, you can use the spread operator. This way, the change in one array is not reflected in the other. For example,

Spread Operator with Object

You can also use the spread operator with object literals. For example,

Here, both obj1 and obj2 properties are added to obj3 using the spread operator.

  • Rest Parameter

When the spread operator is used as a parameter, it is known as the rest parameter.

You can also accept multiple arguments in a function call using the rest parameter. For example,

  • When a single argument is passed to the func() function, the rest parameter takes only one parameter.
  • When three arguments are passed, the rest parameter takes all three parameters.

Note : Using the rest parameter will pass the arguments as array elements.

You can also pass multiple arguments to a function using the spread operator. For example,

If you pass multiple arguments using the spread operator, the function takes the required arguments and ignores the rest.

Note : Spread operator was introduced in ES6 . Some browsers may not support the use of spread syntax. Visit JavaScript Spread Operator support to learn more.

Table of Contents

  • Introduction
  • Copying Arrays
  • Cloning Arrays
  • Spread with Objects

Sorry about that.

Related Tutorials

JavaScript Tutorial

JavaScript Template Literals (Template Strings)

How to use JavaScript’s spread operator

JavaScript is a dynamic and potent language used by developers around the world to enhance web applications with complex, interactive, and rich features.

One such advanced feature in JavaScript’s arsenal is the spread operator . In this article, we’ll dive deep into what the spread operator is, its syntax, and how you can use it effectively in various programming scenarios. Armed with this knowledge, you’ll be able to simplify your code and harness the full potential of JavaScript.

What is the JavaScript Spread Operator?

The JavaScript spread operator ( ... ) is a handy syntax that allows you to ‘spread’ elements of an iterable (such as an array or string) into multiple elements.

Function Calls Made Easier ( ...args )

Simplifying array to arguments.

Imagine a scenario where you have a list of arguments as an array but your function expects individual arguments. Traditionally, you’d use the Function.prototype.apply method to achieve this. But with the spread operator, you can simply pass the array, and it would automatically be expanded to the individual arguments the function expects.

This shorthand not only looks cleaner but also saves you from additional, complicated steps.

Creation and Concatenation in Array Literals

Spreading elements into a new array.

You can use the spread operator within an array literal to incorporate all the elements of another array. This allows for more readable and maintainable code when compared to older methods of array manipulation such as push , splice , or concat .

This method is straightforward when you want to create a new array by merging other arrays without mutating the original ones.

Safe Copy with Spread

To copy an array, you might think of using assignment ( = ), but this only copies the reference, not the actual array. By using the spread operator, you create a shallow copy, thus preserving the integrity of the original array.

However, it’s essential to understand that this method only does a shallow copy. If you have nested arrays or objects, the references inside will still be shared between the original and the copied array.

Enhancing Object Literals

Merging and copying objects.

The spread operator can also be applied in object literals to combine properties of existing objects into a new object. It’s similar to Object.assign() , but the syntax is more concise and easy to read.

Here, clonedObj is a shallow copy of obj1 , and mergedObj is a new object with properties from both obj1 and obj2 . In case of a property conflict, the rightmost property takes precedence, as seen with the property foo .

Important Considerations

While the spread operator can make your code look neater and more intuitive, there are some performance and compatibility considerations you need to be conscious of:

  • Performance : If you’re handling large datasets or performance-critical applications, be mindful of the spread operator’s limitations and alternative methods such as concat() or Object.assign() .
  • Browser Compatibility : Most modern browsers support the spread operator, but always check the Browser Compatibility Data (BCD) tables for detailed information on cross-browser support.
  • Rest vs. Spread : Don’t confuse spread with the rest syntax. The rest syntax looks similar but serves the opposite purpose—condensing multiple elements into a single one.

Let’s give a concluding example to tie everything together:

Conclusion and Practical Example

The spread operator is a flexible and powerful addition to the JavaScript language. Its ability to expand iterables into individual elements can greatly simplify your code and make it much easier to read.

Here’s a practical example to emphasize its utility:

As you can see, the spread operator transformed a two-dimensional array into a flat one with ease.

By understanding and applying the JavaScript spread operator, you can write cleaner, more expressive code. It isn’t just a tool for arrays and objects; it’s a new way of thinking that opens up a plethora of possibilities for JavaScript developers.

Take action : Review your current projects and find opportunities where replacing traditional logic with the spread operator could make your code simpler and more efficient. Happy coding!

Related posts

JavaScript Spread Operator

The JavaScript spread operator is a powerful tool for manipulating arrays and objects. It allows you to spread out the elements of an array or object into separate arguments or variables. The spread operator can also be used to copy or merge arrays and objects.

Why should you use it?

  • It allows you to quickly and easily manipulate arrays and objects.
  • It can be used to copy or merge arrays and objects.
  • It makes it easy to pass multiple arguments to a function.

Spread Operator

The Spread Operator is a new feature of ES6 syntax that allows for the expansion of iterable objects into multiple elements. It is denoted by three consecutive dots (...) and can be used in a variety of ways. This tutorial will cover the basics of using the Spread Operator, as well as some more advanced uses.

Basic Usage

The most basic use of the Spread Operator is to spread an array into individual elements. For example, if you have an array of numbers:

You can use the Spread Operator to spread the array into individual elements:

The Spread Operator can also be used to spread an object into individual elements. For example, if you have an object with two properties:

You can use the Spread Operator to spread the object into individual elements:

Advanced Usage

The Spread Operator can also be used to combine multiple arrays into a single array. For example, if you have two arrays:

You can use the Spread Operator to combine the two arrays into a single array:

The Spread Operator can also be used to combine multiple objects into a single object. For example, if you have two objects:

You can use the Spread Operator to combine the two objects into a single object:

The Spread Operator is a powerful tool that can be used in a variety of ways. It can be used to spread an array or object into individual elements, as well as to combine multiple arrays or objects into a single array or object. It is a great addition to the ES6 syntax, and can make your code more concise and readable.

  • Skip to main content
  • Select language
  • Skip to search
  • Add a translation
  • Print this page
  • Spread operator

A better push

This is an experimental technology, part of the ECMAScript 6 (Harmony) proposal. Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future version of browsers as the spec changes.

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

For function calls:

For array literals:

For destructuring:

A better apply

Example: it is common to use Function.prototype.apply in cases where you want to use an array as arguments to a function.

With ES6 spread you can now write the above as:

Any argument in the argument list can use the spread syntax and it can be used multiple times.

A more powerful array literal

Example: Today if you have an array and want to create a new array with the existing one being part of it, the array literal syntax is no longer sufficient and you have to fall back to imperative code, using a combination of push , splice , concat , etc. With spread syntax this becomes much more succinct:

Just like with spread for argument lists ... can be used anywhere in the array literal and it can be used multiple times.

Apply for new

Example: In ES5 it is not possible to compose new with apply (in ES5 terms apply does a [[Call]] and not a [[Construct]] ). In ES6 the spread syntax naturally supports this:

Example: push is often used to push an array to the end of an existing array. In ES5 this is often done as:

In ES6 with spread this becomes:

Specifications

Browser compatibility.

  • Rest parameters

Document Tags and Contributors

  • Experimental
  • Expérimental
  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • Expressions and operators
  • Numbers and dates
  • Text formatting
  • Indexed collections
  • Keyed collections
  • Working with objects
  • Details of the object model
  • Iterators and generators
  • Meta programming
  • JavaScript basics
  • JavaScript technologies overview
  • Introduction to Object Oriented JavaScript
  • A re-introduction to JavaScript
  • JavaScript data structures
  • Equality comparisons and sameness
  • Inheritance and the prototype chain
  • Strict mode
  • JavaScript typed arrays
  • Memory Management
  • Concurrency model and Event Loop
  • References:
  • Standard built-in objects
  • ArrayBuffer
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • Intl.Collator
  • Intl.DateTimeFormat
  • Intl.NumberFormat
  • ParallelArray
  • ReferenceError
  • StopIteration
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Arithmetic operators
  • Array comprehensions
  • Assignment operators
  • Bitwise operators
  • Comma operator
  • Comparison operators
  • Conditional (ternary) Operator
  • Destructuring assignment
  • Expression closures
  • Generator comprehensions
  • Grouping operator
  • Legacy generator function expression
  • Logical Operators
  • Object initializer
  • Operator precedence
  • Property accessors
  • class expression
  • delete operator
  • function expression
  • function* expression
  • in operator
  • new operator
  • void operator
  • Statements and declarations
  • Legacy generator function
  • for each...in
  • try...catch
  • Arguments object
  • Arrow functions
  • Default parameters
  • Method definitions
  • constructor
  • Lexical grammar
  • Enumerability and ownership of properties
  • Iteration protocols
  • Transitioning to strict mode
  • Template strings
  • Deprecated features
  • New in JavaScript
  • ECMAScript 5 support in Mozilla
  • ECMAScript 6 support in Mozilla
  • ECMAScript 7 support in Mozilla
  • Firefox JavaScript changelog
  • New in JavaScript 1.1
  • New in JavaScript 1.2
  • New in JavaScript 1.3
  • New in JavaScript 1.4
  • New in JavaScript 1.5
  • New in JavaScript 1.6
  • New in JavaScript 1.7
  • New in JavaScript 1.8
  • New in JavaScript 1.8.1
  • New in JavaScript 1.8.5
  • Documentation:
  • All pages index
  • Methods index
  • Properties index
  • Pages tagged "JavaScript"
  • JavaScript doc status
  • The MDN project

JavaScript Spread Operator

Javascript tutorial index.

The JavaScript spread operator ( ... ) is a versatile and powerful tool that simplifies complex operations in your code. It enables you to expand or 'spread' arrays or objects, making your code more readable and efficient. This tutorial delves into the essentials of the spread operator, showcasing its use in arrays, objects, and functions with practical examples.

What is the JavaScript Spread Operator?

The spread operator, represented by three dots ( ... ), expands elements of an iterable (like arrays) or object properties. It was introduced in ES6 and has become a staple in JavaScript programming for its simplicity and efficiency.

When to Use the Spread Operator

Spread Operator is incredibly useful for tasks like combining arrays, copying arrays or objects, and working with functions that take multiple arguments:

Combining Arrays

The spread operator is more efficient for merging arrays than older methods like concat() .

Expanding Arrays

The spread operator can expand the elements of an array:

Copying Arrays

Create a copy of an array without affecting the original:

Expanding Objects

The spread operator isn't just for arrays; it's effective with objects, too:

Merging Objects

Merging objects is straightforward:

Spreading Elements in Function Arguments

Pass array elements as separate arguments with ease:

Advanced Uses of Spread Operator

Destructuring with spread.

Efficiently extract elements while keeping the rest:

Spread in String Manipulation

Turn strings into arrays of individual characters:

In this tutorial, you've explored the JavaScript spread operator, a versatile tool for expanding arrays, merging objects, and simplifying function arguments. You've seen how it can elegantly combine arrays, clone data structures, and facilitate more efficient code. By learning the spread operator, you can increase the readability and functionality of your JavaScript projects, making your coding experience smoother and more productive.

  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter

Spread vs Rest operator in JavaScript ES6

  • JavaScript Spread Operator
  • Operator precedence in JavaScript
  • What is the rest parameter and spread operator in JavaScript ?
  • What is spread, default and rest parameters in JavaScript ?
  • JavaScript in Operator
  • JavaScript Program to Delete Property from Spread Operator
  • JavaScript typeof Operator
  • Arrow operator in ES6 of JavaScript
  • JavaScript String Operators
  • JavaScript Operators Reference
  • What is the use of the += operator in JavaScript ?
  • Subtraction(-) Arithmetic Operator in JavaScript
  • What are Comparison Operators in JavaScript ?
  • Right Shift Assignment(>>=) Operator in JavaScript
  • What is (~~) "double tilde" operator in JavaScript ?
  • Subtraction Assignment( -=) Operator in Javascript
  • OR(||) Logical Operator in JavaScript
  • Explain the purpose of the ‘in’ operator in JavaScript
  • JavaScript Rest parameter
  • How to calculate the number of days between two dates in JavaScript ?
  • Convert a String to an Integer in JavaScript
  • How to append HTML code to a div using JavaScript ?
  • How to Open URL in New Tab using JavaScript ?
  • Difference between var and let in JavaScript
  • How do you run JavaScript script through the Terminal?
  • Remove elements from a JavaScript Array
  • How to read a local text file using JavaScript?
  • JavaScript console.log() Method
  • JavaScript Number toString() Method

Rest and spread operators may appear similar in notation, but they serve distinct purposes in JavaScript, which can sometimes lead to confusion. Let’s delve into their differences and how each is used. Rest and spread operators are both introduced in javascript ES6.

Rest Operator

The rest operator is represented by three dots (…). When used in a function’s parameter list, it catches any extra arguments passed to the function and packs them neatly into an array. This allows functions to handle varying numbers of arguments without explicitly defining them. So, you can think of it as a way to gather up the remaining arguments into an array for easy handling inside the function.

Example: The rest operator gathers all arguments passed to the function after the first one (10 in this case) into an array called rest.

Spread Operator

The spread operator, represented by three dots (…), works by taking all the items in an array and spreading them out, essentially unpacking the array so that each item becomes an individual element. It’s like taking a bunch of items from a box and laying them out separately on a table. This makes it easier to work with the individual items rather than dealing with the entire array as a single entity.

Example: This example shows the use of SPread Operator

DIfference between Spread Operator and Rest Operator

Please login to comment..., similar reads.

  • Web Technologies

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Learn how to use spread operator in JavaScript

    javascript spread operator assignment

  2. #44 What is the Spread Operator?

    javascript spread operator assignment

  3. spread operator in Javascript ES6

    javascript spread operator assignment

  4. JavaScript Spread Operator

    javascript spread operator assignment

  5. Spread Operator in JavaScript ES6

    javascript spread operator assignment

  6. Rest Parameter and Spread Operator in JavaScript ES6

    javascript spread operator assignment

VIDEO

  1. JavaScript: Spread Operator

  2. 59-Javascript Advance 7-Rest & Spread Operator,Array Map,Filter And Reduce Methods,Method Chaining

  3. Javascript Spread Operator

  4. spread operator in javascript

  5. Try THIS JavaScript Trick #coding #programming #javascript

  6. JavaScript: Spread Operator

COMMENTS

  1. Spread syntax (...)

    The spread (...) syntax allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. In an object literal, the spread syntax enumerates the properties of an object and adds the key-value pairs to the object being created. Spread syntax looks exactly like rest syntax.

  2. Destructuring assignment

    Unpacking values from a regular expression match. When the regular expression exec() method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression. Destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if ...

  3. How To Use the Spread Operator (...) in JavaScript

    The JavaScript spread operator (...) expands an iterable (like an array) into more elements. This allows us to quickly copy all or parts of an existing array into another array: Example. Assign the first and second items from numbers to variables and put the rest in an array:

  4. The Practical Usages of JavaScript Spread Operator

    Note that ES2018 expands the spread operator to objects, which is known as object spread. Let's look at some scenarios where you can use the spread operators. JavaScript spread operator and apply() method. See the following compare() function that compares two numbers: function compare (a, b) { return a - b; } Code language: JavaScript ...

  5. JavaScript Object Destructuring, Spread Syntax, and the Rest Parameter

    Spread Syntax in JavaScript. The Spread Syntax (also known as the Spread Operator) is another excellent feature of ES6. As the name indicates, it takes an iterable (like an array) and expands (spreads) it into individual elements. We can also expand objects using the spread syntax and copy its enumerable properties to a new object.

  6. JavaScript Destructuring and the Spread Operator

    Let's look at one last example. function sample(a, b) {. return [a + b, a * b] } let example = sample(2, 5); console.log(example) Function to Add and Multiply two numbers. We have a function here which accepts two numbers. It returns an array adding them and multiplying them and logs them into the console.

  7. Spread syntax

    Spread syntax (other than in the case of spread properties) can be applied only to iterable objects: var obj = {'key1': 'value1'}; var array = [...obj]; // TypeError: obj is not iterable Spread with many values. When using spread syntax for function calls, be aware of the possibility of exceeding the JavaScript engine's argument length limit.

  8. Understanding Destructuring, Rest Parameters, and Spread Syntax in

    The default assignment for object destructuring creates new variables with the same name as the object property. If you do not want the new variable to have the same name as the property name, you also have the option of renaming the new variable by using a colon (:) to decide a new name, as seen with noteId in the following:// Assign a custom name to a destructured value const {id: noteId ...

  9. JavaScript Spread Operator

    Here, both variables arr1 and arr2 are referring to the same array. Hence the change in one variable results in the change in both variables. However, if you want to copy arrays so that they do not refer to the same array, you can use the spread operator.

  10. Understanding the JavaScript Spread Operator

    The spread operator, …, was first introduced in ES6. It quickly became one of the most popular features. ... Here's an example of the rest parameter used in a destructuring assignment: Destructuring with the rest parameter. ... This is the second and final part of the Understanding the JavaScript Spread Operator — From Beginner to Expert ...

  11. How to use JavaScript's spread operator

    The JavaScript spread operator (...) is a handy syntax that allows you to 'spread' elements of an iterable (such as an array or string) into multiple elements. ... To copy an array, you might think of using assignment (=), but this only copies the reference, not the actual array. By using the spread operator, you create a shallow copy, thus ...

  12. JavaScript Spread Operator

    The Spread Operator is a powerful tool that can be used in a variety of ways. It can be used to spread an array or object into individual elements, as well as to combine multiple arrays or objects into a single array or object. It is a great addition to the ES6 syntax, and can make your code more concise and readable.

  13. JavaScript Spread Operator

    The Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 value is expected. It allows us the privilege to obtain a list of parameters from an array. The syntax of the Spread operator is the same as the Rest parameter but it works opposite of it.

  14. Spread operator

    The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected. ... JavaScript; Tutorials: JavaScript Guide. Introduction; Grammar and types; ... Assignment operators; Bitwise operators; Comma operator; Comparison operators; Conditional ...

  15. JavaScript Spread Operator

    The JavaScript spread operator ( ...) is a versatile and powerful tool that simplifies complex operations in your code. It enables you to expand or 'spread' arrays or objects, making your code more readable and efficient. This tutorial delves into the essentials of the spread operator, showcasing its use in arrays, objects, and functions with ...

  16. javascript

    49. If you know the name of the property ( a in the example below), then @crowder's answer is perfect: const o3 = {...o1, a: "updated a"}; console.log(o3); If the property name is in a variable, then you need to use Computed Property names syntax: let variable = 'foo'. const o4 = {...o1, [variable]: "updated foo"};

  17. Spread vs Rest operator in JavaScript ES6

    Spread vs Rest operator in JavaScript ES6. Rest and spread operators may appear similar in notation, but they serve distinct purposes in JavaScript, which can sometimes lead to confusion. Let's delve into their differences and how each is used. Rest and spread operators are both introduced in javascript ES6.

  18. Expressions and operators

    This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more. At a high level, an expression is a valid unit of code that resolves to a value. There are two types of expressions: those that have side effects (such as assigning values) and those that ...

  19. javascript

    Thus, 'the spread operator' is objectively more correctly referred to as 'spread syntax'. 1 The term 'punctuator' refers to punctuators in ECMAScript 2015 and later specifications. These symbols include syntax components and operators, and are punctators of the language. ... is a punctuator itself, but the term 'spread syntax' refers to the ...

  20. Assignment (=)

    The assignment operator is completely different from the equals (=) sign used as syntactic separators in other locations, which include:Initializers of var, let, and const declarations; Default values of destructuring; Default parameters; Initializers of class fields; All these places accept an assignment expression on the right-hand side of the =, so if you have multiple equals signs chained ...

  21. Using the spread operator multiple times in JavaScript

    @madox2: If we consider operators a special form of functions (which it is in other languages), then we could say that we can use an operator everywhere were we can use a function call. E.g. instead of var foo = add(1, 2); we can write var foo = 1 + 2;.However, we cannot replace var foo = spread(arr); with var foo = ...arr;.There is no such thing as a standalone spread operator, it is simply ...