The three dots (...) in JavaScript

anuragaffection

Anurag Affection

Posted on April 19, 2024

The three dots (...) in JavaScript

The three dots (...) in JavaScript are typically used for two purposes:

1. Spread Syntax:

It allows an iterable (like an array or a string) to be expanded into individual elements. For example:

const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // arr2 is [1, 2, 3, 4, 5]

Enter fullscreen mode Exit fullscreen mode

2. Rest Parameters:

It collects all remaining elements into an array. For example:

function sum(...numbers) {
    return numbers.reduce((acc, curr) => acc + curr, 0);
}
sum(1, 2, 3); // returns 6

Enter fullscreen mode Exit fullscreen mode

Object Rest Properties

It's a feature introduced in ECMAScript 2018 (ES9). It allows you to extract all the remaining properties of an object into a new object. Here's how it works:

const obj = { a: 1, b: 2, c: 3 };
const { a, ...rest } = obj;

console.log(a); // 1
console.log(rest); // { b: 2, c: 3 }

Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
anuragaffection
Anurag Affection

Posted on April 19, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related