paint-brush
Javascript Cheatsheet: Spread Operators  by@imsabir
554 reads
554 reads

Javascript Cheatsheet: Spread Operators

by MohammedMarch 14th, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

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. The spread operator makes deep copies of data if the data is not nested. When you have nested data in an array or object the spread operator will create a deep copy of the top most data and a shallow copy of nested data.
featured image - Javascript Cheatsheet: Spread Operators
Mohammed HackerNoon profile picture


You might have heard about Spread Operators. We use them in everyday development.


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 by comparing the normal arrays method, so this can be helpful to everyone including those who didn't use it as well as those who are also familiar with it.



  1. String to Array with Spread:

    Just spread the variable with and get the array.

    
    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:

    Here spread both the array as [..arr1, …arr2] and get one single 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 ] 


  1. Cloning Array using Spread:

    Cloning of an array can be done in various ways. Here is a demo. The demo shows both ways; with and without spread operators:


//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 behaves like this?


Stay tuned I am bringing another blog for explaining this. Why separate blogs?because it is required to understand the concepts of data types and it’s out of the context of this blog.


In short: The spread operator makes deep copies of data if the data is not nested. When you have nested data in an array or object the spread operator will create a deep copy of the topmost data and a shallow copy of the nested data.


Shallow Copy:shallow copy of an object is a copy whose properties share the same references (point to the same underlying values) as those of the source object from which the copy was made. As a result, when you change either the source of the copy, you may also cause the other object to change too


Deep Copy:deep copy of an object is a copy whose properties do not share the same references (point to the same underlying values) as those of the source object from which the copy was made. As a result, when you change either the source of the copy, you can be assured you're not causing the other object to change too; that is, you won't unintentionally be causing changes to the source or copy that you don't expect.


  1. 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 ]
    
    


  2. Nodelist to Array:


    //create nodelist object 
    const h1s = document.querySelectorAll('h1');
    //convert nodelist to an array
    const h1sArray = [...h1s]
    


  3. 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
    


  4. 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'}
    



Cheers!



This article was first published here.


바카라사이트 바카라사이트 온라인바카라