Best Website-BuildersBest Website-Builders
    What's Hot

    Trump Back on Facebook Days Before Expected Indictment

    March 17, 2023

    Menindee: Millions of dead fish wash up near Australian town

    March 17, 2023

    The Papers: Passport strike and arrest warrant for Putin

    March 17, 2023
    Facebook Twitter Instagram
    Facebook Twitter Instagram
    Best Website-BuildersBest Website-Builders
    • Home
    • CSS

      Mānoa: Independent Report: “Appropriate and Timely” Response to UH Mānoa Athletics Concerns

      March 17, 2023

      Weak natural gas prices spur fuel switching in Europe

      March 17, 2023

      Kenya route presents supporters with new allies with 50 ministerial positions

      March 17, 2023

      Franz Ferdinand Leads 50 in New Daft Punk Book After Daft

      March 17, 2023

      Franz Ferdinand Leads 50 in New Daft Punk Book After Daft

      March 17, 2023
    • Joomla

      How Superior Web Hosting Support Can Drive Business Success

      March 17, 2023

      PANDACU Studio Website Development Cooperation First Page Sage SEO Dsign Chicago adstargets Cardinal Digital Agency

      March 16, 2023

      Bluehost Review: Best Solution for Your Web Hosting Needs? – WISH-TV | Indianapolis News | Indiana Weather

      March 15, 2023

      What’s New in Search? SEO Strategies for 2023

      March 15, 2023

      What’s New in Search? SEO Strategies for 2023

      March 15, 2023
    • PHP

      Children with cystic fibrosis aren’t automatically eligible for ‘make-a-wish’

      March 17, 2023

      Josh Duggar’s prison sentence extended

      March 17, 2023

      AI arms race heats up this week

      March 17, 2023

      Iranian girls detained for dancing TikTok in public

      March 17, 2023

      Financial YouTuber sued for promoting FTX

      March 17, 2023
    • UX

      Remember User Experience in Zero Trust Journeys

      March 17, 2023

      Best MA Sports Betting App User Experience

      March 17, 2023

      Chancery & Circuit Court & Estate Transfers – www.elizabethton.com

      March 17, 2023

      The Generative AI Revolution will Enable Anyone to Create Games

      March 17, 2023

      Using Technology to Create a Better Customer Experience

      March 17, 2023
    • Web Builders
      1. Web Design
      2. View All

      What Comes First in Website Development — Design or Copy?

      February 2, 2023

      Modern Campus Honors Best Higher Education Websites of 2022

      February 2, 2023

      Premier SEO Consultant in Las Vegas, Nevada with Unparalleled Customer Service

      February 2, 2023

      Can Religious Freedom Be Saved? This group is racing the clock to teach America’s first freedom

      February 2, 2023

      How i Create New Google Account

      February 7, 2023

      CWT powers tools for meeting and event planners

      January 31, 2023

      Best Website Builder – Website Builders

      January 24, 2023

      Is There A Market For Rap-Themed Slot Games? – Rap Review

      January 19, 2023
    • WordPress

      Google Photos could soon bring its AI editing capabilities to videos

      March 17, 2023

      Windows 11 update coming soon to make your PC more stable

      March 17, 2023

      Sorry, Ryzen 9 7950X doesn’t hit 6.3 GHz

      March 17, 2023

      FakeCalls Android banking scam is back

      March 17, 2023

      A much cheaper RTX 4060 GPU could be on the horizon if this leaked image is true

      March 17, 2023
    • Realtoz
      • Our Other Sites
    • More News
    Best Website-BuildersBest Website-Builders
    Home » How to Use the Spread Operator in JavaScript—SitePoint
    JavaScript

    How to Use the Spread Operator in JavaScript—SitePoint

    websitebuildersnowBy websitebuildersnowOctober 5, 2022No Comments5 Mins Read
    Facebook Twitter LinkedIn Telegram Pinterest Tumblr Reddit WhatsApp Email
    Share
    Facebook Twitter LinkedIn Pinterest Email


    In this tutorial, we’ll explore different ways to use spread operators in JavaScript and the key differences between spread and rest operators.

    three dots (...), the JavaScript spread operator was introduced in ES6. Can be used to expand the elements of collections and arrays into single individual elements.

    You can use the spread operator to create and duplicate arrays and objects, pass arrays as function parameters, and remove duplicates from arrays.

    syntax

    The spread operator can only be used with iterable objects. Must be used immediately before an iterable object, without isolation. for example:

    console.log(...arr);
    

    function parameter

    Take the Math.min() method as an example. This method accepts at least one number as a parameter and returns the smallest number among the passed parameters.

    If you have an array of numbers and you want to find the minimum value of these numbers, you can pass the elements one by one using the index or use the apply() method to pass the elements one by one without using the spread operator. must pass. Array as a parameter. for example:

    const numbers = [15, 13, 100, 20];
    const minNumber = Math.min.apply(null, numbers);
    console.log(minNumber); 
    

    the first parameter is nullbecause the first parameter is used to change the value of this of the calling function.

    The spread operator is a more convenient and readable solution for passing array elements as parameters to functions. for example:

    const numbers = [15, 13, 100, 20];
    const minNumber = Math.min(...numbers);
    console.log(numbers); 
    

    You can see it in this live example:

    look at the pen
    Using spread operator in function JS by SitePoint (@SitePoint)
    with a code pen.

    create an array

    You can use the spread operator to create new arrays from existing arrays or other iterable objects with the Symbol.iterator() method. these are, for...of loop.

    For example, it can be used to clone an array. If you just assign the values ​​of the existing array to the new array, any changes to the new array will update the existing array.

    const numbers = [15, 13, 100, 20];
    const clonedNumbers = numbers;
    clonedNumbers.push(24);
    console.log(clonedNumbers); 
    console.log(numbers); 
    

    The spread operator allows an existing array to be duplicated into a new array, and changes made to the new array do not affect the existing array.

    const numbers = [15, 13, 100, 20];
    const clonedNumbers = [...numbers];
    clonedNumbers.push(24);
    console.log(clonedNumbers); 
    console.log(numbers); 
    

    Note that this only replicates 1D arrays. It doesn’t work with multidimensional arrays.

    You can also use the spread operator to concatenate multiple arrays into one. for example:

    const evenNumbers = [2, 4, 6, 8];
    const oddNumbers = [1, 3, 5, 7];
    const allNumbers = [...evenNumbers, ...oddNumbers];
    console.log(...allNumbers); 
    

    You can also use the spread operator on strings to create an array where each item is a character in the string.

    const str = 'Hello, World!';
    const strArr = [...str];
    console.log(strArr); 
    

    create an object

    The spread operator can be used to create objects in various ways.

    Can be used for shallow duplication of another object. for example:

    const obj = { name: 'Mark', age: 20};
    const clonedObj = { ...obj };
    console.log(clonedObj); 
    

    It can also be used to combine multiple objects into one. for example:

    const obj1 = { name: 'Mark', age: 20};
    const obj2 = { occupation: 'Student' };
    const clonedObj = { ...obj1, ...obj2 };
    console.log(clonedObj); 
    

    Note that if objects share the same property name, the value from the last object spread will be used. for example:

    const obj1 = { name: 'Mark', age: 20};
    const obj2 = { age: 30 };
    const clonedObj = { ...obj1, ...obj2 };
    console.log(clonedObj); 
    

    You can create an object from an array using the spread operator. The index in the array becomes the property, and the value at that index becomes the value of the property. for example:

    const numbers = [15, 13, 100, 20];
    const obj = { ...numbers };
    console.log(obj); 
    

    It can also be used to create objects from strings. Similarly, the index in the string becomes the property, and the character at that index becomes the value of the property. for example:

    const str = 'Hello, World!';
    const obj = { ...str };
    console.log(obj); 
    

    Convert NodeList to Array

    A NodeList is a collection of nodes, which are elements in the document. Elements are accessed through methods in the collection such as: item again entrieswhich is different from an array.

    You can convert a NodeList to an array using the spread operator. for example:

    const nodeList = document.querySelectorAll('div');
    console.log(nodeList.item(0)); 
    const nodeArray = [...nodeList];
    console.log(nodeList[0]); 
    

    remove duplicates from array

    A Set object is a collection that stores only unique values. As with NodeList , we can use the spread operator to convert Set to an array.

    Since Set stores only unique values, it can be combined with the spread operator to remove duplicates from an array. for example:

    const duplicatesArr = [1, 2, 3, 2, 1, 3];
    const uniqueArr = [...new Set(duplicatesArr)];
    console.log(duplicatesArr); 
    console.log(uniqueArr); 
    

    Spread and rest operators

    The rest of the operators are also the 3-dot operator (...), but it serves a different purpose. You can use the rest operator in a function’s parameter list to indicate that this function accepts an undefined number of parameters. These parameters can be treated as arrays.

    for example:

    function calculateSum(...funcArgs) {
      let sum = 0;
      for (const arg of funcArgs) {
        sum += arg;
      }
    
      return sum;
    }
    

    In this example, the rest operator is calculateSum function. Then loop through the items in the array and sum them to calculate the sum.

    Then one by one the variables calculateSum Use a function as an argument, or pass an array element as an argument using the spread operator.

    console.log(calculateSum(1, 2, 3)); 
    const numbers = [1, 2, 3];
    console.log(calculateSum(...numbers)); 
    

    Conclusion

    Diffusion operators let you do more with fewer lines of code while maintaining code readability. It can be used with iterables to pass parameters to functions or create arrays and objects from other iterables.

    Related reading:



    Source link

    Share this:

    • Tweet
    • Email
    • Pocket
    • Mastodon
    • WhatsApp
    • Telegram
    • Share on Tumblr
    • Print
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Telegram Email
    Previous ArticleMercedes head of UX design defends big screens in modern cars
    Next Article Best small business website builders in 2022
    websitebuildersnow
    • Website

    Related Posts

    Arrow functions and regular functions in JavaScript

    March 17, 2023

    Versatile Advanced AI Takes First Step: GPT-4 Creates a Simple Game in JavaScript and Takes the Bar Exam | NEWS.AMTEC

    March 17, 2023

    Sockets roll out wrappers to protect developers from bad packages • The Register

    March 16, 2023
    Add A Comment

    Leave a Reply Cancel reply

    Top Posts

    Subscribe to Updates

    Get the latest sports news from SportsSite about soccer, football and tennis.

    Advertisement
    Demo

    This website provides information about CSS and other things. Keep Supporting Us With the Latest News and we Will Provide the Best Of Our To Makes You Updated All Around The World News. Keep Sporting US.

    Facebook Twitter Instagram Pinterest YouTube
    Top Insights

    Trump Back on Facebook Days Before Expected Indictment

    March 17, 2023

    Menindee: Millions of dead fish wash up near Australian town

    March 17, 2023

    The Papers: Passport strike and arrest warrant for Putin

    March 17, 2023
    Get Informed

    Subscribe to Updates

    Get the latest creative news from FooBar about art, design and business.

    © 2023 bestwebsite-builders. Designed by bestwebsite-builders.
    • Home
    • About us
    • Contact us
    • DMCA
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.