Search code examples
javascriptarraysnode.jsweb-scrapingnightmare

what are those triple dot inside the array? marked it with a comment


I was learning how to web scrape in nodejs and came across this kind of array. What is the meaning?

articles = [               //WHAT IS THIS
    ...articles,
    ...new_articles
];

Solution

  • When we see three dots (…) in the code, it's either rest parameters or the spread operator.

    Rest parameters: When three dots (…) is at the end of function parameters it will gather the rest of the list of arguments into an array.

    spread operator: Expands elements of an array (or all iterables) into places where multiple elements can fit.

    yourFunction(arg1, arg2, ...argN) { // used like rest parameter here
      console.log(arg1);
      console.log(arg2);
      console.log(argN);
    }
    
    var inputs = ["a", "b", "c", "d", "e", "f"];
    yourFunction(...inputs); // used like spread operator here
    

    Another example of the spread-operator:

    const array1 = ['item1', 'item2', 'item3'];
    const array2 = ['item5', 'item6', 'item7'];
    
    const items = [...array1, 'item4', ...array2];
    
    console.log(items);
    // 'item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7'