Spread Operator
Spread Operator is a feature in JavaScript and other programming languages that allows you to spread an array into individual elements. It is a convenient way to pass an array as arguments to a function or to create a new array from an existing one.
How Spread Operator Works
The spread operator is represented by three dots (...). When used in front of an array, the spread operator expands the array into individual elements. For example, the following code creates a new array by spreading the numbers array:
const numbers = [1, 2, 3, 4, 5]; const newNumbers = [...numbers];
The newNumbers array will now contain the individual elements from the numbers array: [1, 2, 3, 4, 5]
Using Spread Operator
The spread operator can be used in various scenarios, including:
Passing Arrays as Arguments
Spread operator can be used to pass an array as an argument to a function that expects individual elements. For example:
function sum(a, b, c) {
return a + b + c;
}
const numbers = [1, 2, 3];
const result = sum(...numbers); // 6Creating New Arrays
Spread operator can be used to create a new array by combining elements from multiple arrays. For example:
const numbers1 = [1, 2, 3]; const numbers2 = [4, 5, 6]; const combinedNumbers = [...numbers1, ...numbers2]; // [1, 2, 3, 4, 5, 6]