Show List
Spread Operator
The spread operator (...
) in JavaScript allows an iterable such as an array expression or string to be expanded or spread into individual elements. It's particularly useful in situations where you want to use the elements of an array or the characters of a string as arguments or elements in another array or function call. The spread operator was introduced in ES6 (ECMAScript 2015). Here are some examples to illustrate its usage:
- Spread operator with arrays:
// Example 1: Combining arrays
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combinedArray = [...arr1, ...arr2];
console.log(combinedArray); // Output: [1, 2, 3, 4, 5, 6]
// Example 2: Copying arrays
const originalArray = [1, 2, 3];
const copiedArray = [...originalArray];
console.log(copiedArray); // Output: [1, 2, 3]
// Example 3: Passing elements of an array as arguments to a function
const numbers = [1, 2, 3];
function sum(a, b, c) {
return a + b + c;
}
console.log(sum(...numbers)); // Output: 6
- Spread operator with strings:
// Example: Splitting a string into characters
const str = "hello";
const chars = [...str];
console.log(chars); // Output: ['h', 'e', 'l', 'l', 'o']
- Spread operator with objects (introduced in ES2018):
// Example: Copying object properties into a new object
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
console.log(obj2); // Output: { a: 1, b: 2, c: 3 }
- Spread operator with function calls:
// Example: Math operations with arrays
const numbers = [1, 2, 3];
console.log(Math.max(...numbers)); // Output: 3 (using spread to pass elements of numbers array as arguments)
// Example: Concatenating arrays using push method with spread operator
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
arr1.push(...arr2);
console.log(arr1); // Output: [1, 2, 3, 4, 5, 6]
In summary, the spread operator allows you to easily manipulate arrays, strings, and objects by spreading their elements or properties into new arrays, strings, or objects. It's a powerful feature for working with collections and function arguments in JavaScript.
Leave a Comment