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>

    var parts = ['two', 'three'];
    var numbers = ['one',, 'four', 'five'];





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.

   function f(a, b, ...args) {

  var out = f(1, 2, 3, 4, 5);

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, } = { 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

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