Skip to content

Three dots in JavaScript | Example code

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

Simple example code use three dots … in two different ways as 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]

Do 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

Your email address will not be published. Required fields are marked *