Computer Science

Javascript Spread And Rest

Javascript Spread and Rest are two features that allow developers to manipulate arrays and objects in a more efficient way. The spread operator allows for the expansion of an array or object into individual elements, while the rest parameter allows for the gathering of multiple elements into an array. These features can simplify code and improve performance.

Written by Perlego with AI-assistance

2 Key excerpts on "Javascript Spread And Rest"

  • Book cover image for: Professional JavaScript for Web Developers
    • Matt Frisbie(Author)
    • 2019(Publication Date)
    • Wrox
      (Publisher)
    In the ECMAScript 2018 specification, all the elegance of rest and spread operators in arrays is now also available inside object literals. This allows you to merge objects or collect properties into new objects.

    Rest Operator

    The rest operator allows you to use a single rest operator when destructuring an object to collect all remaining unspecified enumerable properties into a single object. This can be done as follows:
    const person = { name: 'Matt', age: 27, job: 'Engineer' };
    const { name, …remainingData } = person;
    console.log(name); // Matt console.log(remainingData); // { age: 27, job: 'Engineer' }
    The rest operator can be used at most once per object literal and must be listed last. Because there can be only a single rest operator per object literal, it is possible to nest the rest operators. When nesting, because there is no ambiguity about which elements of the property subtree are allocated to any given rest operator, the resulting objects will never overlap with respect to their contents:
    const person = { name: 'Matt', age: 27, job: { title: 'Engineer', level: 10 } };
    const { name, job: { title, …remainingJobData }, …remainingPersonData } = person;
    console.log(name); // Matt console.log(title); // Engineer console.log(remainingPersonData); // { age: 27 } console.log(remainingJobData); // { level: 10 } const { …a, job } = person; // SyntaxError: Rest element must be last element
    The rest operator performs a shallow copy between objects, so object references will be copied instead of creating entire object clones:
    const person = { name: 'Matt', age: 27, job: { title: 'Engineer', level: 10 } }; const { …remainingData } = person; console.log(person === remainingData); // false
    console.log(person.job === remainingData.job); // true
    The rest operator will copy all enumerable own properties, including symbols:
    const s = Symbol();
    const foo = { a: 1, [s]: 2, b: 3 }
    const {a, …remainingData} = foo; console.log(remainingData); // { b: 3, Symbol(): 2 }

    Spread Operator

    The spread operator allows you to join two objects together in a fashion similar to array concatenation. The spread operator applied to an inner object will perform a shallow copy of all enumerable own properties, including symbols, into the outer object:
  • Book cover image for: Web Developer's Reference Guide
    • Joshua Johanan, Talha Khan, Ricardo Zea(Authors)
    • 2016(Publication Date)
    • Packt Publishing
      (Publisher)
    ) preceding a parameter.
    Here is an example showing the rest parameter: //Rest Parameter function sum(…nums) { var result = 0; nums.forEach(function(number) { result += number; }); return result; } console.log(sum(1)); // 1 console.log(sum(1, 2, 3)); // 6 The named parameter becomes an array containing the rest of the parameters. Adding more than one named argument may cause syntax error.

    Spread operator

    Spread operator is very similar to the rest parameter, but it allows us to split the array to individual arguments, which are then passed to the function as separate arguments. Here is an example showing the spread operator: //Spread Operator functionsum2(a, b, c) { return a + b + c; } varargs = [1, 2]; console.log(sum(…args, …args, 3)); // 6 Here is an example showing the usage of default, rest, and spread parameters:
    function sum() { return ; } console.log(sum( (1, 2) //Spread Operator //Rest Parameter //Default Parameter Values //Default Parameter Values functioninc(num, increment = 1) { returnnum + increment; } console.log(inc(2, 2)); // 4 console.log(inc(4)); // 5

    Bindings

    The let keyword is a new var . The declaration syntax for the let keyword is the same as for var . You can basically replace var with let to declare a variable but keep its scope to the current code:
    functiongetCuisine(condition) { if (condition) { letcuisine = "Mediterranean"; // other code returncuisine; } else { // cuisine does not exist here return null; } // cuisine does not exist here }
    Variables defined using const are considered to be constants, so the value cannot be changed once set. For this reason, every const variable has to be initialized:
    // Valid constant const ITEMS = 10; // Syntax error: missing initialization const ITEM;

    Iterators and the for...of operator

    We use iterators to allow customization of an object's iteration method/behavior, such as CLRIE numerable or Java Iterable. Generalize the for..in operator to custom iterator-based iteration with for..of
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.