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]
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
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 }
Top comments (2)
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:
Thank You, I am new here.