This content originally appeared on DEV Community and was authored by DEV Community
What is the Spread Operator?
This syntax is used to succinctly pass multiple values from either an Array or Object to an expression where elements are expected. Examples are the best way to show this.
Arrays
Combining arrays
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let combinedArr = [...arr1, ...arr2];
// combinedArr = [1, 2, 3, 4, 5, 6]
let arr1 = [1, 2, 3];
let arr2 = [4, ...arr1, 5, 6];
// arr2 = [4, 1, 2, 3, 5, 6]
Copying an array
let arr = [1, 2, 3];
let arrCopy = [...arr];
// arrCoppy = [1, 2, 3]
// changing arr will not effect arrCopy
Objects
Merge Objects
let obj1 = { id: 1, name: 'Aden' };
let obj2 = { birthday: '2022-02-04', hairColor: 'Brown' };
let combinedObj = { ...obj1, ...obj2 };
// combinedObj = { id: 1, name: 'Aden', birthday: '2022-02-04', hairColor: 'Brown' }
Note: Merging objects with like attributes may not behave the way you expect
let obj1 = { id: 1, name: 'Aden' };
let obj2 = { id: 2, name: 'Bob' };
let combinedObj = { ...obj1, ...obj2 };
// combinedObj = { id: 2, name: 'Bob' }
A Common use case in React
import { useState } from "react";
const App = () => {
const [input, setInput] = useState("");
const [list, setList] = useState([]);
const addButtonClick = () => {
// We use the spread operator to add
// an item to the end of the array
setList((list) => [...list, input]);
};
return (
<div>
<input
type="text"
value={input}
onChange={(e) => {
setInput(e.target.value);
}}
/>
<button onClick={addButtonClick}>Add</button>
<ul>
{list.map((item) => {
return <li key={Math.random()}>{item}</li>;
})}
</ul>
</div>
);
};
export default App;
More information about the spread syntax can be found in the MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
Leave comment if you have any questions or feedback.
This content originally appeared on DEV Community and was authored by DEV Community
DEV Community | Sciencx (2022-03-07T01:14:05+00:00) Spread Operator in JavaScript (…). Retrieved from https://www.scien.cx/2022/03/07/spread-operator-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.