DEV Community

Anurag Affection
Anurag Affection

Posted on

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

Top comments (2)

Collapse
 
schemetastic profile image
Schemetastic (Rodrigo) •

Hey! Cool post!

Did you know you could highlight your code?

Just add the name of the coding language after the initial 3 backticks of a code block.
```js
let hello = "dev!";
```

would output:

let hello = "dev!";
Enter fullscreen mode Exit fullscreen mode
Collapse
 
anuragaffection profile image
Anurag Affection • • Edited

Thank You, I am new here.