Spread Syntax (...) - JavaScript - MDN - Mozilla
Có thể bạn quan tâm
- Skip to main content
- Skip to search
This feature is well established and works across many devices and browser versions. It’s been available across browsers since October 2015.
- Learn more
- See full compatibility
- Report feedback
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. In a way, spread syntax is the opposite of rest syntax. Spread syntax "expands" an array into its elements, while rest syntax collects multiple elements and "condenses" them into a single element. See rest parameters and rest property.
In this article
- Try it
- Syntax
- Description
- Examples
- Specifications
- Browser compatibility
- See also
Try it
function sum(x, y, z) { return x + y + z; } const numbers = [1, 2, 3]; console.log(sum(...numbers)); // Expected output: 6 console.log(sum.apply(null, numbers)); // Expected output: 6Syntax
jsmyFunction(a, ...iterableObj, b) [1, ...iterableObj, '4', 'five', 6] { ...obj, key: 'value' }Description
Spread syntax can be used when all elements from an object or array need to be included in a new array or object, or should be applied one-by-one in a function call's arguments list. There are three distinct places that accept the spread syntax:
- Function arguments list (myFunction(a, ...iterableObj, b))
- Array literals ([1, ...iterableObj, '4', 'five', 6])
- Object literals ({ ...obj, key: 'value' })
Although the syntax looks the same, they come with slightly different semantics.
Only iterable values, like Array and String, can be spread in array literals and argument lists. Many objects are not iterable, including all plain objects that lack a Symbol.iterator method:
jsconst obj = { key1: "value1" }; const array = [...obj]; // TypeError: obj is not iterableOn the other hand, spreading in object literals enumerates the own properties of the value. For typical arrays, all indices are enumerable own properties, so arrays can be spread into objects.
jsconst array = [1, 2, 3]; const obj = { ...array }; // { 0: 1, 1: 2, 2: 3 }All primitives can be spread in objects. Only strings have enumerable own properties, and spreading anything else doesn't create properties on the new object.
jsconst obj = { ...true, ..."test", ...10 }; // { '0': 't', '1': 'e', '2': 's', '3': 't' }When using spread syntax for function calls, be aware of the possibility of exceeding the JavaScript engine's argument length limit. See Function.prototype.apply() for more details.
Examples
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.
jsfunction myFunction(x, y, z) {} const args = [0, 1, 2]; myFunction.apply(null, args);With spread syntax the above can be written as:
jsfunction myFunction(x, y, z) {} const args = [0, 1, 2]; myFunction(...args);Any argument in the argument list can use spread syntax, and the spread syntax can be used multiple times.
jsfunction myFunction(v, w, x, y, z) {} const args = [0, 1]; myFunction(-1, ...args, 2, ...[3]);Apply for new operator
When calling a constructor with new, it's not possible to directly use an array and apply(), because apply() calls the target function instead of constructing it, which means, among other things, that new.target will be undefined. However, an array can be easily used with new thanks to spread syntax:
jsconst dateFields = [1970, 0, 1]; // 1 Jan 1970 const d = new Date(...dateFields);Spread in array literals
A more powerful array literal
Without spread syntax, the array literal syntax is no longer sufficient to create a new array using an existing array as one part of it. Instead, imperative code must be used using a combination of methods, including push(), splice(), concat(), etc. With spread syntax, this becomes much more succinct:
jsconst parts = ["shoulders", "knees"]; const lyrics = ["head", ...parts, "and", "toes"]; // ["head", "shoulders", "knees", "and", "toes"]Just like spread for argument lists, ... can be used anywhere in the array literal, and may be used more than once.
Copying an array
You can use spread syntax to make a shallow copy of an array. Each array element retains its identity without getting copied.
jsconst arr = [1, 2, 3]; const arr2 = [...arr]; // like arr.slice() arr2.push(4); // arr2 becomes [1, 2, 3, 4] // arr remains unaffectedSpread syntax effectively goes one level deep while copying an array. Therefore, it may be unsuitable for copying multidimensional arrays. The same is true with Object.assign() — no native operation in JavaScript does a deep clone. The web API method structuredClone() allows deep copying values of certain supported types. See shallow copy for more details.
jsconst a = [[1], [2], [3]]; const b = [...a]; b.shift().shift(); // 1 // Oh no! Now array 'a' is affected as well: console.log(a); // [[], [2], [3]]A better way to concatenate arrays
Array.prototype.concat() is often used to concatenate an array to the end of an existing array. Without spread syntax, this is done as:
jslet arr1 = [0, 1, 2]; const arr2 = [3, 4, 5]; // Append all items from arr2 onto arr1 arr1 = arr1.concat(arr2);With spread syntax this becomes:
jslet arr1 = [0, 1, 2]; const arr2 = [3, 4, 5]; arr1 = [...arr1, ...arr2]; // arr1 is now [0, 1, 2, 3, 4, 5]Array.prototype.unshift() is often used to insert an array of values at the start of an existing array. Without spread syntax, this is done as:
jsconst arr1 = [0, 1, 2]; const arr2 = [3, 4, 5]; // Prepend all items from arr2 onto arr1 Array.prototype.unshift.apply(arr1, arr2); console.log(arr1); // [3, 4, 5, 0, 1, 2]With spread syntax, this becomes:
jslet arr1 = [0, 1, 2]; const arr2 = [3, 4, 5]; arr1 = [...arr2, ...arr1]; console.log(arr1); // [3, 4, 5, 0, 1, 2]Note: Unlike unshift(), this creates a new arr1, instead of modifying the original arr1 array in-place.
Conditionally adding values to an array
You can make an element present or absent in an array literal, depending on a condition, using a conditional operator.
jsconst isSummer = false; const fruits = ["apple", "banana", ...(isSummer ? ["watermelon"] : [])]; // ['apple', 'banana']When the condition is false, we spread an empty array, so that nothing gets added to the final array. Note that this is different from the following:
jsconst fruits = ["apple", "banana", isSummer ? "watermelon" : undefined]; // ['apple', 'banana', undefined]In this case, an extra undefined element is added when isSummer is false, and this element will be visited by methods such as Array.prototype.map().
Spread in object literals
Copying and merging objects
You can use spread syntax to merge multiple objects into one new object.
jsconst obj1 = { foo: "bar", x: 42 }; const obj2 = { bar: "baz", y: 13 }; const mergedObj = { ...obj1, ...obj2 }; // { foo: "bar", x: 42, bar: "baz", y: 13 }A single spread creates a shallow copy of the original object (but without non-enumerable properties and without copying the prototype), similar to copying an array.
jsconst clonedObj = { ...obj1 }; // { foo: "bar", x: 42 }Overriding properties
When one object is spread into another object, or when multiple objects are spread into one object, and properties with identical names are encountered, the property takes the last value assigned while remaining in the position it was originally set.
jsconst obj1 = { foo: "bar", x: 42 }; const obj2 = { foo: "baz", y: 13 }; const mergedObj = { x: 41, ...obj1, ...obj2, y: 9 }; // { x: 42, foo: "baz", y: 9 }Conditionally adding properties to an object
You can make an element present or absent in an object literal, depending on a condition, using a conditional operator.
jsconst isSummer = false; const fruits = { apple: 10, banana: 5, ...(isSummer ? { watermelon: 30 } : {}), }; // { apple: 10, banana: 5 }The case where the condition is false is an empty object, so that nothing gets spread into the final object. Note that this is different from the following:
jsconst fruits = { apple: 10, banana: 5, watermelon: isSummer ? 30 : undefined, }; // { apple: 10, banana: 5, watermelon: undefined }In this case, the watermelon property is always present and will be visited by methods such as Object.keys().
Because primitives can be spread into objects as well, and from the observation that all falsy values do not have enumerable properties, you can simply use a logical AND operator:
jsconst isSummer = false; const fruits = { apple: 10, banana: 5, ...(isSummer && { watermelon: 30 }), };In this case, if isSummer is any falsy value, no property will be created on the fruits object.
Comparing with Object.assign()
Note that Object.assign() can be used to mutate an object, whereas spread syntax can't.
jsconst obj1 = { foo: "bar", x: 42 }; Object.assign(obj1, { x: 1337 }); console.log(obj1); // { foo: "bar", x: 1337 }In addition, Object.assign() triggers setters on the target object, whereas spread syntax does not.
jsconst objectAssign = Object.assign( { set foo(val) { console.log(val); }, }, { foo: 1 }, ); // Logs "1"; objectAssign.foo is still the original setter const spread = { set foo(val) { console.log(val); }, ...{ foo: 1 }, }; // Nothing is logged; spread.foo is 1You cannot naively re-implement the Object.assign() function through a single spreading:
jsconst obj1 = { foo: "bar", x: 42 }; const obj2 = { foo: "baz", y: 13 }; const merge = (...objects) => ({ ...objects }); const mergedObj1 = merge(obj1, obj2); // { 0: { foo: 'bar', x: 42 }, 1: { foo: 'baz', y: 13 } } const mergedObj2 = merge({}, obj1, obj2); // { 0: {}, 1: { foo: 'bar', x: 42 }, 2: { foo: 'baz', y: 13 } }In the above example, the spread syntax does not work as one might expect: it spreads an array of arguments into the object literal, due to the rest parameter. Here is an implementation of merge using the spread syntax, whose behavior is similar to Object.assign(), except that it doesn't trigger setters, nor mutates any object:
jsconst obj1 = { foo: "bar", x: 42 }; const obj2 = { foo: "baz", y: 13 }; const merge = (...objects) => objects.reduce((acc, cur) => ({ ...acc, ...cur })); const mergedObj = merge(obj1, obj2); // { foo: 'baz', x: 42, y: 13 }Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification# prod-SpreadElement |
| ECMAScript® 2026 Language Specification# prod-ArgumentList |
| ECMAScript® 2026 Language Specification# prod-PropertyDefinition |
Browser compatibility
See also
- Rest parameters
- Rest property
- Function.prototype.apply()
Help improve MDN
Was this page helpful to you? Yes No Learn how to contributeThis page was last modified on Jul 20, 2025 by MDN contributors.
View this page on GitHub • Report a problem with this content Filter sidebar- JavaScript
- Tutorials and guides
- JavaScript Guide
- Introduction
- Grammar and types
- Control flow and error handling
- Loops and iteration
- Functions
- Expressions and operators
- Numbers and strings
- Representing dates & times
- Regular expressions
- Indexed collections
- Keyed collections
- Working with objects
- Using classes
- Using promises
- JavaScript typed arrays
- Iterators and generators
- Resource management
- Internationalization
- JavaScript modules
- Intermediate
- Language overview
- JavaScript data structures
- Equality comparisons and sameness
- Enumerability and ownership of properties
- Closures
- Advanced
- Inheritance and the prototype chain
- Meta programming
- Memory Management
- References
- Built-in objects
- AggregateError
- Array
- ArrayBuffer
- AsyncDisposableStack
- AsyncFunction
- AsyncGenerator
- AsyncGeneratorFunction
- AsyncIterator
- Atomics
- BigInt
- BigInt64Array
- BigUint64Array
- Boolean
- DataView
- Date
- decodeURI()
- decodeURIComponent()
- DisposableStack
- encodeURI()
- encodeURIComponent()
- Error
- escape() Deprecated
- eval()
- EvalError
- FinalizationRegistry
- Float16Array
- Float32Array
- Float64Array
- Function
- Generator
- GeneratorFunction
- globalThis
- Infinity
- Int8Array
- Int16Array
- Int32Array
- InternalError Non-standard
- Intl
- isFinite()
- isNaN()
- Iterator
- JSON
- Map
- Math
- NaN
- Number
- Object
- parseFloat()
- parseInt()
- Promise
- Proxy
- RangeError
- ReferenceError
- Reflect
- RegExp
- Set
- SharedArrayBuffer
- String
- SuppressedError
- Symbol
- SyntaxError
- Temporal
- TypedArray
- TypeError
- Uint8Array
- Uint8ClampedArray
- Uint16Array
- Uint32Array
- undefined
- unescape() Deprecated
- URIError
- WeakMap
- WeakRef
- WeakSet
- Expressions & operators
- Addition (+)
- Addition assignment (+=)
- Assignment (=)
- async function expression
- async function* expression
- await
- Bitwise AND (&)
- Bitwise AND assignment (&=)
- Bitwise NOT (~)
- Bitwise OR (|)
- Bitwise OR assignment (|=)
- Bitwise XOR (^)
- Bitwise XOR assignment (^=)
- class expression
- Comma operator (,)
- Conditional (ternary) operator
- Decrement (--)
- delete
- Destructuring
- Division (/)
- Division assignment (/=)
- Equality (==)
- Exponentiation (**)
- Exponentiation assignment (**=)
- function expression
- function* expression
- Greater than (>)
- Greater than or equal (>=)
- Grouping operator ( )
- import.meta
- import.meta.resolve()
- import()
- in
- Increment (++)
- Inequality (!=)
- instanceof
- Left shift (<<)
- Left shift assignment (<<=)
- Less than (<)
- Less than or equal (<=)
- Logical AND (&&)
- Logical AND assignment (&&=)
- Logical NOT (!)
- Logical OR (||)
- Logical OR assignment (||=)
- Multiplication (*)
- Multiplication assignment (*=)
- new
- new.target
- null
- Nullish coalescing assignment (??=)
- Nullish coalescing operator (??)
- Object initializer
- Operator precedence
- Optional chaining (?.)
- Property accessors
- Remainder (%)
- Remainder assignment (%=)
- Right shift (>>)
- Right shift assignment (>>=)
- Spread syntax (...)
- Strict equality (===)
- Strict inequality (!==)
- Subtraction (-)
- Subtraction assignment (-=)
- super
- this
- typeof
- Unary negation (-)
- Unary plus (+)
- Unsigned right shift (>>>)
- Unsigned right shift assignment (>>>=)
- void operator
- yield
- yield*
- Statements & declarations
- async function
- async function*
- await using
- Block statement
- break
- class
- const
- continue
- debugger
- do...while
- Empty statement
- export
- Expression statement
- for
- for await...of
- for...in
- for...of
- function
- function*
- if...else
- import
- Import attributes
- Labeled statement
- let
- return
- switch
- throw
- try...catch
- using
- var
- while
- with Deprecated
- Functions
- Arrow function expressions
- Default parameters
- get
- Method definitions
- Rest parameters
- set
- The arguments object
- [Symbol.iterator]()
- callee Deprecated
- length
- Classes
- constructor
- extends
- Private elements
- Public class fields
- static
- Static initialization blocks
- Regular expressions
- Backreference: \1, \2
- Capturing group: (...)
- Character class escape: \d, \D, \w, \W, \s, \S
- Character class: [...], [^...]
- Character escape: \n, \u{...}
- Disjunction: |
- Input boundary assertion: ^, $
- Literal character: a, b
- Lookahead assertion: (?=...), (?!...)
- Lookbehind assertion: (?<=...), (?<!...)
- Modifier: (?ims-ims:...)
- Named backreference: \k<name>
- Named capturing group: (?<name>...)
- Non-capturing group: (?:...)
- Quantifier: *, +, ?, {n}, {n,}, {n,m}
- Unicode character class escape: \p{...}, \P{...}
- Wildcard: .
- Word boundary assertion: \b, \B
- Errors
- AggregateError: No Promise in Promise.any was resolved
- Error: Permission denied to access property "x"
- InternalError: too much recursion
- RangeError: argument is not a valid code point
- RangeError: BigInt division by zero
- RangeError: BigInt negative exponent
- RangeError: form must be one of 'NFC', 'NFD', 'NFKC', or 'NFKD'
- 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
- RangeError: x can't be converted to BigInt because it isn't an integer
- ReferenceError: "x" is not defined
- ReferenceError: assignment to undeclared variable "x"
- ReferenceError: can't access lexical declaration 'X' before initialization
- ReferenceError: must call super constructor before using 'this' in derived class constructor
- ReferenceError: super() called twice in derived class constructor
- SyntaxError: 'arguments'/'eval' can't be defined or assigned to in strict mode code
- SyntaxError: "0"-prefixed octal literals are deprecated
- SyntaxError: "use strict" not allowed in function with non-simple parameters
- SyntaxError: "x" is a reserved identifier
- SyntaxError: \ at end of pattern
- 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: arguments is not valid in fields
- SyntaxError: await is only valid in async functions, async generators and modules
- SyntaxError: await/yield expression can't be used in parameter
- SyntaxError: cannot use `??` unparenthesized within `||` and `&&` expressions
- SyntaxError: character class escape cannot be used in class range in regular expression
- SyntaxError: continue must be inside loop
- SyntaxError: duplicate capture group name in regular expression
- SyntaxError: duplicate formal argument x
- SyntaxError: for-in loop head declarations may not have initializers
- SyntaxError: function statement requires a name
- SyntaxError: functions cannot be labelled
- SyntaxError: getter and setter for private name #x should either be both static or non-static
- SyntaxError: getter functions must have no arguments
- SyntaxError: identifier starts immediately after numeric literal
- SyntaxError: illegal character
- SyntaxError: import declarations may only appear at top level of a module
- SyntaxError: incomplete quantifier in regular expression
- SyntaxError: invalid assignment left-hand side
- SyntaxError: invalid BigInt syntax
- SyntaxError: invalid capture group name in regular expression
- SyntaxError: invalid character in class in regular expression
- SyntaxError: invalid class set operation in regular expression
- SyntaxError: invalid decimal escape in regular expression
- SyntaxError: invalid identity escape in regular expression
- SyntaxError: invalid named capture reference in regular expression
- SyntaxError: invalid property name in regular expression
- SyntaxError: invalid range in character class
- SyntaxError: invalid regexp group
- SyntaxError: invalid regular expression flag "x"
- SyntaxError: invalid unicode escape in regular expression
- SyntaxError: JSON.parse: bad parsing
- SyntaxError: label not found
- SyntaxError: missing : after property id
- SyntaxError: missing ) after argument list
- SyntaxError: missing ) after condition
- SyntaxError: missing ] after element list
- SyntaxError: missing } after function body
- SyntaxError: missing } after property list
- SyntaxError: missing = in const declaration
- SyntaxError: missing formal parameter
- SyntaxError: missing name after . operator
- SyntaxError: missing variable name
- SyntaxError: negated character class with strings in regular expression
- SyntaxError: new keyword cannot be used with an optional chain
- SyntaxError: nothing to repeat
- SyntaxError: numbers out of order in {} quantifier.
- SyntaxError: octal escape sequences can't be used in untagged template literals or in strict mode code
- SyntaxError: parameter after rest parameter
- SyntaxError: private fields can't be deleted
- SyntaxError: property name __proto__ appears more than once in object literal
- SyntaxError: raw bracket is not allowed in regular expression with unicode flag
- SyntaxError: redeclaration of formal parameter "x"
- SyntaxError: reference to undeclared private field or method #x
- SyntaxError: rest parameter may not have a default
- SyntaxError: return not in function
- SyntaxError: setter functions must have one argument
- SyntaxError: string literal contains an unescaped line break
- SyntaxError: super() is only valid in derived class constructors
- SyntaxError: tagged template cannot be used with optional chain
- SyntaxError: Unexpected '#' used outside of class body
- SyntaxError: Unexpected token
- SyntaxError: unlabeled break must be inside loop or switch
- SyntaxError: unparenthesized unary expression can't appear on the left-hand side of '**'
- SyntaxError: use of super property/member accesses only valid within methods or eval code within methods
- SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
- TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed
- TypeError: 'x' is not iterable
- 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: already executing generator
- TypeError: BigInt value can't be serialized in JSON
- TypeError: calling a builtin X constructor without new is forbidden
- TypeError: can't access/set private field or method: object is not the right class
- TypeError: can't assign to property "x" on "y": not an object
- TypeError: can't convert BigInt to number
- TypeError: can't convert x to BigInt
- 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: can't set prototype of this object
- TypeError: can't set prototype: it would cause a prototype chain cycle
- TypeError: cannot use 'in' operator to search for 'x' in 'y'
- TypeError: class constructors must be invoked with 'new'
- TypeError: cyclic object value
- TypeError: derived class constructor returned invalid value x
- TypeError: getting private setter-only property
- TypeError: Initializing an object twice is an error with private fields/methods
- TypeError: invalid 'instanceof' operand 'x'
- TypeError: invalid Array.prototype.sort argument
- TypeError: invalid assignment to const "x"
- TypeError: Iterator/AsyncIterator constructor can't be used directly
- TypeError: matchAll/replaceAll must be called with a global RegExp
- TypeError: More arguments needed
- TypeError: null/undefined has no properties
- TypeError: property "x" is non-configurable and can't be deleted
- TypeError: Reduce of empty array with no initial value
- TypeError: setting getter-only property "x"
- TypeError: WeakSet key/WeakMap value 'x' must be an object or an unregistered symbol
- TypeError: X.prototype.y called on incompatible type
- URIError: malformed URI sequence
- Warning: -file- is being assigned a //# sourceMappingURL, but already has one
- Warning: unreachable code after return statement
- Misc
- JavaScript technologies overview
- Execution model
- Lexical grammar
- Iteration protocols
- Strict mode
- Template literals
- Trailing commas
- Deprecated features
Từ khóa » Cách Dọc Spread
-
SPREAD | Phát âm Trong Tiếng Anh - Cambridge Dictionary
-
Cách Phát âm Spread Trong Tiếng Anh - Forvo
-
Spread - Wiktionary Tiếng Việt
-
Cấu Trúc Và Cách Dùng Spread Trong Tiếng Anh - StudyTiengAnh
-
Spread Nghĩa Là Gì ? | Từ Điển Anh Việt EzyDict
-
SPREAD - Nghĩa Trong Tiếng Tiếng Việt - Từ điển
-
Spread Tiếng Anh Là Gì? - Chickgolden
-
Spread Trong Tiếng Việt, Dịch, Tiếng Anh - Từ điển Tiếng Việt | Glosbe
-
Vietgle Tra Từ - Định Nghĩa Của Từ 'spread' Trong Từ điển Lạc Việt
-
Spread Position Nghĩa Là Gì Trong Tiếng Việt? - English Sticky
-
Câu Ví Dụ,định Nghĩa Và Cách Sử Dụng Của"Spread" - LIVESHAREWIKI
-
Spread Là Gì? Spread Trong Forex Có Gì Mà Thu Hút? - Coin28
-
Spread The Branch - (Bước 3 - Tỏa Cành) - Bản Tin Nóng