Monday, 3 February 2020

What is three dot (...) in Javascript?



In this article we explain what is the three dots (...) in javascript.

Three dots (...) called Spread Attributes or Spread Operator or Rest Operator. It has come in Ecama script(ES6).

It allows an array expression or string or anything which can be iterating  to be expanded in places where zero or more arguments for function calls or elements for the array are expected.

Merge two arrays:

var arr1 = [1,2,3];
var arr2 = [4,5,6];

arr1 = [...arr1, ...arr2];
console.log(arr1);  
//[1, 2, 3, 4, 5, 6]

Copying array:
var arr = [1, 2, 3];
var arr2 = [...arr];

console.log(arr); 
//[1, 2, 3]

Spread operator is used for a reference type :
let person= {
    name: 'Ram',
    age: 54 
}
person1= person;

person1.name = "Raj";

console.log( person.name); // output: Raj
This is called reference type, one object affects other objects because they are shareable in memory. if you want to getting value separately means spread memory both variable.

 let person= {
        name: 'Ram',
        age: 54 
    }
person2 = {...person};

person2.name = "Raj";

console.log(person.name); // output: Ram