Rest Operator in ES6 - 05

Rest Operator:

function person(...anyName) {
 for (let i = 0; i < anyName.length; i++) {
   console.log("Arguments passed", anyName[i]);
 }
}
 
person("Mozahedul", "Islam", "student");
 
const man = (...item) => {
 item.map((organ) => {
   console.log("man ==> ", organ);
 });
};
 
man("Black", "eyes", "finger", "hands");
 
const woman = (...item) => {
 item.forEach((organ) => {
   console.log("woman ==> ", organ);
 });
};
 
woman("lipStick", "snow", "cream");
 
const girl = (name, title, ...item) => {
 console.log(name, title);
 item.forEach((organ) => {
   console.log("girl ==> ", organ);
 });
};
 
girl("ramisa", "houseWife", "band", "lotion", "hand wash", "soap");

Explanation: 

  • When we pass arguments with the rest operator, then the arguments are stored in an array as the name of the rest operator.
  • Now we can access each of the arguments by applying a for loop or ES6 array method like map(), forEach(), filter(), and reduce().
  • If we know the arguments, then we can set the name for those arguments and apply the rest operator to the rest of the argument.
 

Post a Comment

Previous Post Next Post