Skip to content

Three dots in JavaScript | Example code

  • by

The three dots in JavaScript are the spread/rest operator. The three dots… are called spread attributes which, as the name represents, allow an expression to be expanded.

And Rest Parameters/operator makes it possible to take all of the arguments to a function in one array.

Three dots in JavaScript

A simple example code uses three dots … in two different ways as a spread operator and rest operator.

Spread Operators

The spread operator is used to expand elements of an iterable (like an array) into places where multiple elements can fit.

<!DOCTYPE html>
<html>
<body>

  <script>
    var parts = ['two', 'three'];
    var numbers = ['one', ...parts, 'four', 'five'];

    console.log(numbers)

  </script>

</body>
</html> 

Output:

Three dots in JavaScript

Copying Arrays

When we wanted a copy of an array, we used to have the Array.prototype.slice() method. But, you can do the same with the spread operator.

var arr = [1,2,3];
var arr2 = [...arr];
// arr2 = [1,2,3]

Rest Parameters

ES6 also has three dots (...) which indicates a rest parameter that collects all remaining arguments of a function into an array.

<script>
   function f(a, b, ...args) {
    console.log(args);
  }

  var out = f(1, 2, 3, 4, 5);
  console.log(out)
</script>

Output: [3, 4, 5]

Ellipsis in Object Destructuring:

In the ECMAScript proposal (not yet part of the standard as of my knowledge cutoff in September 2021), the three dots can be used to create a shallow copy of an object with specific properties omitted during object restructuring.

const { x, y, ...rest } = { x: 1, y: 2, z: 3, w: 4 };
console.log(x, y); // Output: 1 2
console.log(rest); // Output: { z: 3, w: 4 }

The above example destructures the x and y properties from the object, and the rest of the properties are gathered into a new object called rest.

Comment if you have any doubts or suggestions on this JS Operator topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading