In JavaScript, the three dots operator is called the spread operator, which allows an iterable (e.g., an array or a string) to be expanded into individual elements. It is denoted by three dots (i.e., "...").
Here's an example of how to use the spread operator:
javascript// Example 1: Combining arrays
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const combinedArray = [...array1, ...array2]; // [1, 2, 3, 4, 5, 6]
// Example 2: Copying arrays
const originalArray = [1, 2, 3];
const copiedArray = [...originalArray]; // [1, 2, 3]
console.log(originalArray === copiedArray); // false
// Example 3: Passing arguments to a function
function sum(a, b, c) {
return a + b + c;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers)); // 6
// Example 4: Converting a string to an array
const str = "hello";
const chars = [...str]; // ["h", "e", "l", "l", "o"]
In Example 1, the spread operator is used to combine two arrays into a new array. In Example 2, the spread operator is used to make a copy of an existing array. In Example 3, the spread operator is used to pass an array of arguments to a function. In Example 4, the spread operator is used to convert a string into an array of individual characters.
Note that the spread operator can only be used with iterable objects, such as arrays and strings. Additionally, it is only supported in ES6 (ECMAScript 2015) and newer versions of JavaScript.