Best Website-BuildersBest Website-Builders
    What's Hot

    Person dies in listeria outbreak linked to cheese

    March 24, 2023

    Reddit – Dive into anything

    March 24, 2023

    Derbyshire PC to keep job after using database to find woman on Instagram

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

      Federal agencies still use cell phones as tracking beacons

      March 24, 2023

      41 House Builders Score 5 Stars for Customer Satisfaction – Show House

      March 24, 2023

      CAS earns Chief Secretary or better in new review

      March 24, 2023

      Determining the survival benefit of postoperative radiation therapy in patients with pT1-3N1M0 rectal cancer who underwent total mesorectal resection: a retrospective analysis BMC Gastroenterology

      March 23, 2023

      What you need to know about CSS Profiles

      March 23, 2023
    • Joomla

      Save Thousands On Web Hosting With iBrave, Now Only $86

      March 23, 2023

      In Vitro Transcription Services Market Analysis, Research Study with Shanghai Zhishuo Biotechnology Co., Yunzhou Biotechnology Co.

      March 23, 2023

      Current state of UK content management systems

      March 23, 2023

      Reseller Hosting Business: Important Q&A

      March 21, 2023

      Web Hosting: 8 Elements Every Entrepreneur Should Look For

      March 20, 2023
    • PHP

      ‘Vanderpump Rules’ star Raquel Levis intends to drop Shaana Shay’s restraining order

      March 24, 2023

      Beyoncé announces new fashion collaboration with Balmain

      March 24, 2023

      All shower trends on TikTok: 12 products to try

      March 24, 2023

      Why do I get gas and bloating on air travel?

      March 24, 2023

      Ben Affleck and Matt Damon’s shared bank account

      March 24, 2023
    • UX

      SMS pumping attacks and how to mitigate them

      March 24, 2023

      Q&A with Debbie Levitt on UX research and design — Visual Studio Magazine

      March 24, 2023

      New book examines effects of European arrivals in Mexico: UNM Newsroom

      March 24, 2023

      When and how to use HTML sitemaps for SEO and UX

      March 24, 2023

      What is an infographic resume? | | Career

      March 24, 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

      Framework’s DIY laptop puts Apple and Microsoft to shame with upgradeable CPUs and makes me excited for the future

      March 24, 2023

      New Python info-stealing malware uses Unicode to avoid detection

      March 24, 2023

      4 reasons Rescue is the remote support champion

      March 24, 2023

      Intel exits 5G and LTE PC business

      March 24, 2023

      These next-level phishing scams use PayPal or Google Docs to steal your data

      March 24, 2023
    • Realtoz
      • Our Other Sites
    • More News
    Best Website-BuildersBest Website-Builders
    Home » Quick tip: how to use the spread operator in JavaScript
    JavaScript

    Quick tip: how to use the spread operator in JavaScript

    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 Also 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 and to 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

    Four ways to remove specific items from a JavaScript array

    March 24, 2023

    Toolkit enables JavaScript developers to program embedded devices

    March 23, 2023

    What Will Pass This Year’s Minnesota Legislature and What Will Happen

    March 23, 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

    Person dies in listeria outbreak linked to cheese

    March 24, 2023

    Reddit – Dive into anything

    March 24, 2023

    Derbyshire PC to keep job after using database to find woman on Instagram

    March 24, 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.