*It’s used with both arrays and objects, in arrays it’s used when:
1. Building an Array
2. passing arguments into a function
1- Building an Array:
const arr = [5, 6, 7]; // without the spread operator ? const badArr = [1, 2, 3, 4, arr[0], arr[1], arr[2]]; console.log(badArr); // [1, 2, 3, 4, 5, 6, 7] // with the spread operator ? const goodArr = [1, 2, 3, 4, ...arr]; console.log(goodArr); // [1, 2, 3, 4, 5, 6, 7]
as you can see, the spread operator makes things much easier.
if you again wanted the individual elements of the expanded array, use the spread operator:
console.log(...goodArr); // 1 2 3 4 5 6 7 //the line above is just like writing this code: console.log(1, 2, 3, 4, 5, 6, 7); // 1 2 3 4 5 6 7
const foods = ['chicken', 'meat', 'rice']; const Newfoods = [...foods, 'pizza ']; console.log(Newfoods); // ['chicken', 'meat', 'rice', 'pizza ']
console.log(foods); // ['chicken', 'meat', 'rice']
Two useful use cases of the spread operator with arrays:
1.creating a copy of an array:
const arrOriginal = [1, 2, 3, 4, 5]; const arrCopy = [...arrOriginal]; console.log(arrCopy); // [1, 2, 3, 4, 5]
2.merging two or more arrays:
const arr1 = ['A', 'B', 'C']; const arr2 = ['D', 'E', 'F']; const mergedArr = [...arr1, ...arr2]; console.log(mergedArr); // ['A', 'B', 'C', 'D', 'E', 'F']
const str = 'spongeBob'; const letters = [...str, 'squarePants']; console.log(letters); // ['s', 'p', 'o', 'n', 'g', 'e', 'B', 'o', 'b', 'squarePants']
console.log(`spelling sponge bob's name: ${...str}`); // Expression expected
2- passing arguments into a function
const arr = [5, 6, 7]; // without the spread operator ? const badArr = [1, 2, 3, 4, arr[0], arr[1], arr[2]]; console.log(badArr); // [1, 2, 3, 4, 5, 6, 7] // with the spread operator ? const goodArr = [1, 2, 3, 4, ...arr]; console.log(goodArr); // [1, 2, 3, 4, 5, 6, 7]
console.log(...goodArr); // 1 2 3 4 5 6 7 //the line above is just like writing this code: console.log(1, 2, 3, 4, 5, 6, 7); // 1 2 3 4 5 6 7
Hope you understood everything here, if you have any questions feel free to ask in the comments section, THANKS for reading ?
The above is the detailed content of JavaScript Spread Operator. For more information, please follow other related articles on the PHP Chinese website!