Spread Syntax in Arrays
Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 48 of 65.
The spread syntax (...) allows an iterable, such as an array, to be expanded in places where zero or more arguments or elements are expected. It provides a concise way to perform operations like combining arrays or copying arrays.
Here are some common use cases:
1. Combining arrays:
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4, 5, 6]2. Creating a shallow copy of an array:
const original = [1, 2, 3];
const copy = [...original];
console.log(copy); // [1, 2, 3]3. Adding elements to an array:
const numbers = [1, 2, 3];
const moreNumbers = [0, ...numbers, 4];
console.log(moreNumbers); // [0, 1, 2, 3, 4]4. Passing array elements as function arguments:
function sum(a, b, c) {
return a + b + c;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers)); // 6Challenge
EasyCreate a function called mergeArr that takes two arrays of numbers as arguments. The function should:
- Merge the two arrays using the spread operator
- Remove any duplicate numbers
- Return the resulting array
Cheat sheet
The spread syntax (...) allows an iterable to be expanded in places where zero or more arguments or elements are expected.
Combining arrays:
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4, 5, 6]Creating a shallow copy:
const original = [1, 2, 3];
const copy = [...original];
console.log(copy); // [1, 2, 3]Adding elements to an array:
const numbers = [1, 2, 3];
const moreNumbers = [0, ...numbers, 4];
console.log(moreNumbers); // [0, 1, 2, 3, 4]Passing array elements as function arguments:
function sum(a, b, c) {
return a + b + c;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers)); // 6Try it yourself
function mergeArr(arr1, arr2) {
// Write your code here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String FundamentalsIterate Over StringsTemplate LiteralsString MethodsRecap - String Weaver4JSON Part 2
Iterate Over JSONNested JSONJSON Optional ChainingShallow And Deep CopyRecap - Bicycle ShopRecap - Solar System10Manage Festival System
Project OverviewAdd Movies & Venues2Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays5Sets Part 1
What Is A Set?Iterating Over SetsAdding An ElementRemoving An ElementChecking If An Element ExistsSize And Is EmptyCopy And ClearRecap - Basic Of Sets8Arrays Interesting Topics
Array DestructuringSpread Syntax in ArraysSparse ArraysRecap - Arrays Workshop3JSON Part 1
What is a JSON?Check If Key ExistsObject MethodsThe Spread Operator Part 1The Spread Operator Part 2Remove KeysRecap - JSON Manipulate Keys