You might have heard about this Spread Operators and be are using it too in everyday Developement.
Syntax: (...
)
Definition: According to MDN Web Docs
Spread syntax (...) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.
Use case scenario: We will see this with comparing normal arrays method, so this can be helpful to everyone including who didn't used it as well as who is also familiar with it.
1. String to Array with Spread:
const myName = "Jhon Doe";
const convertMyNameToArray = [...myName];
console.log(convertMyNameToArray);
//Output: Array (8)[ J,h,o,n, ,D,o,e ]
2. Spread for Merging Array:
const array1 = [50,150,250];
const array2 = [100,200,300];
const mergedArray = [
...array1,
...array2
]
console.log(mergedArray);
//Output: Array(6)[ 50,150,250,100,200,300 ]
3. Cloning Array using Spread:
//Without Spread Operator:
const animals = ['lion','tiger','zebra'];
const wildAnimals = animals;
wildAnimals.push('elephant')
console.log(animals);
//Output: Array (4)[ lion,tiger,zebra,elephant ]
//Here original array is affected although we pushed in cloned array.
//With Spread Operator:
const animals = ['lion','tiger','zebra'];
const wildAnimals = [...animals];
wildAnimals.push('elephant');
console.log(animals)
//Output: Array (3)[ lion,tiger,zebra ]
//Here original array is NOT affected
Do you know why it behave like this? Stay tune I am brining another blog for explaining this. Why seprate blog? because required to understand the concepts of data types and its right now out of context of this blog.
4. Set Object to Array
//Creating a new Set Object
const flowersSet = new Set(['rose','lotus','lilly']);
console.log(flowersSet);
//Output: Set (3) { rose=> rose,lotus=> lotus,lilly=> lilly }
//Converting the Set Object to Array
const newFlowerArray = [...flowersSet];
console.log(newFlowerArray);
//Output: Array (3)[ rose,lotus,lilly ]
5. Nodelist to Array:
//create nodelist object
const h1s = document.querySelectorAll('h1');
//convert nodelist to an array
const h1sArray = [...h1s];
5. Min or Max value from an array:
//USING APPLY
const ages = [21,52,55]
const elderPerson = Math.min.apply(Math,ages); //21
const younderPerson = Math.max.apply(Math,ages); //55
//USING Spread
const elderPerson = Math.min(...ages); //21
const younderPerson = Math.max(...ages); //55
Spread Operator for Objects:
const user1 = {
name: 'Jhon',
age: 21,
};
const user2 = {
name: "Doe",
dob: "5th Jan 1990"
};
const mergedUsers = {...user1, ...user2};
console.log(mergedUsers)
//Output: {name: 'Doe', age: 21, dob: '5th Jan 1990'}
Follow @msabir for more such updates.
Cheers!
Stay tune for next blog !!