Spread and Rest Operator

Next Gen JS for learning ReactJS, mostly used is Spread.

by M Rahul Reddy

JavaScript

console.clear();

/*Spread Operator is used on both arrays and objects:
1- Conveniently copy arrays
2- Add properties to an object
3- Safely copying old object
*/

/* Spread Operator in Arrays */
console.log("Spread in Arrays....")
const numbers = [1,2,3];
//Usage of Spread
const newNumbers = [...numbers,4] // pulled out 'numbers' elememt
//number as an element
const numElem = [numbers,4]

console.log("New Numbers = ",newNumbers)
console.log("Numbers = ",numbers)
console.log("Number as an Element = ",numElem)


/* Spread Operator in Objects */
console.log("Spread in Objects....")

const person = {
  name: 'Rahul'
};

const newPerson = {
...person, // taking old person object and distributing it in the newPerson. 
age: '26'
};
console.log("New Person = ",newPerson)
/*on distributing old object in a new object it also OVERLAPS THE EXISTING PROPERTY WITH THE LATEST/LAST ONE*/
console.log("Deep dive(overlap) Spread Operator....");
var obj = {a:1, b:2};
var before = {
	a: 3,
  ...obj
};
var after = {
  ...obj,
  a:3
};
console.log('before', before); // {a:1, b:2}
console.log('after', after); // {a:3, b:2}

console.log("Rest Operator....")

const searchMe = (...params) => { //the 3 dots are used as rest operator that merges the arguments into an array and thus we use array method filter below
return params.filter(el => el === 1) // check for value and equality // inline arrow function
}

console.log("Rest ",searchMe(1,2,3))