DEV Community

Adeyemi Raji
Adeyemi Raji

Posted on

Javascript Spread and Rest Operator syntax explained...

In this tutorial, we will learn about JavaScript spread and rest operator with the help of detailed examples

The spread operator in JavaScript 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. It is represented by three dots (...).

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.

let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5, 6];
console.log(arr2); // [1, 2, 3, 4, 5, 6]

Enter fullscreen mode Exit fullscreen mode

You can also use the spread operator to spread the elements of an array into a function call:

let arr = [1, 2, 3];
console.log(Math.max(...arr)); // 3

Enter fullscreen mode Exit fullscreen mode


let [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]

The rest operator is similar to the spread operator, but it is used to capture the remaining elements of an array. It is represented by three dots (...) and is usually used in conjunction with destructuring assignment.

For example, you can use the rest operator to capture the remaining elements of an array into a new one:

let [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]

Enter fullscreen mode Exit fullscreen mode

You can also use the rest operator to capture the remaining elements of an array into a function argument:

function print(first, second, ...rest) {
    console.log(first);
    console.log(second);
    console.log(rest);
}

print(1, 2, 3, 4, 5); //1
2
[3,4,5]

Enter fullscreen mode Exit fullscreen mode

further usage of spread operator with function:

const add = function (...numbers) {
let sum = 0;
for( let i = 0; i < numbers.length; i++ ) sum += numbers[i];
console.log(sum); 
};
add()3,2,5)
add(3, 4, 1, 4, 6, 7, 5, 2)
add(9, 2, 1, 4)

Enter fullscreen mode Exit fullscreen mode

Hope you have a better understanding of the spread and rest operator after this explanation.

Top comments (0)