Back to articles
Spread vs Rest Operators in JavaScript

Spread vs Rest Operators in JavaScript

via Dev.toHiral

JavaScript gives us powerful tools to work with data more easily—and two of the most useful are the spread (...) and rest (...) operators. Even though they look the same, they behave very differently depending on where you use them. Let’s break it down step by step. What the Spread Operator Does The spread operator is used to expand (spread out) values. Think of it like unpacking items from a box. Example with Arrays const numbers = [ 1 , 2 , 3 ]; const newNumbers = [... numbers , 4 , 5 ]; console . log ( newNumbers ); // [1, 2, 3, 4, 5] Here, ...numbers takes each element and expands it into the new array. What the Rest Operator Does The rest operator does the opposite—it collects multiple values into one. Think of it like packing items into a box. function sum (... nums ) { return nums . reduce (( total , num ) => total + num , 0 ); } console . log ( sum ( 1 , 2 , 3 , 4 )); // 10 ...nums collects all arguments into a single array. Using Spread with Arrays and Objects Array const arr1

Continue reading on Dev.to

Opens in a new tab

Read Full Article
2 views

Related Articles