Monday, December 5, 2016

JavaScript Evolution ECMAScript 6 - Function with Rest Parameter

JavaScript functions have a built-in object called the argument object. The argument object contains an array of the argument used when the function is called. This kind of function called variadic function.
x = displayTags("A","B","C");
function displayTags() {
  for (let i in arguments){
    let tag = arguments[i];
    addTagTopic(tag);
  }
}
The variadic function gives a major problem where we add an argument, its break our code.
x = displayTags("A","B","C");
function displayTags(targetElement) {   let target = findElement(targetElement);   for (let i in arguments){     let tag = arguments[i]; // Break since the last argument it is no longer a tag.     addTagTopic(tag);   } }
The new rest parameter syntax allows us to represent an indefinite number of arguments as an Array. This way, changes to function signature are less likely to break the code.
function displayTags(...tags) {
  for (let i in tags){
    let tag = tags[i];
    addTagTopic(tag);
  }
}
// Rest parameter must go last.
function displayTags(targetElement, ...tags) {
  let target = findElement(targetElement);
  for (let i in tags){
    let tag = tags[i];
    addTagTopic(tag);
  }
}

No comments:

Post a Comment