Javascript Function Argument Passing merge default Object values

Description

Javascript Function Argument Passing merge default Object values


// Merging an argument object with an object literal containing default values
function describeBook(args) {
  let fArgs = defaults({
    name: 'Unknown',
    pages: 1,/*from w ww  . ja va 2  s .  c om*/
    chapters: 1,
    author: 'John Doe',
    published: 'Unknown',
    type: 'Paperback',
    section: 'Unclassified Books'
  }, args);
  
  console.log("Name: " + fArgs.name);
  console.log("Pages: " + fArgs.pages);
  console.log("Chapters: " + fArgs.chapters);
  console.log("Author: " + fArgs.author);
  console.log("Publish Date: " + fArgs.published);
  console.log("Type: " + fArgs.type);
  console.log("Section: " + fArgs.section);  
}
// Ensures that an object contains, at the very least a specific
// list of key / value pairs with default values
function defaults(defaultValues, originalArgs) {
  // ensure that we are dealing with a valid object
  if (originalArgs && typeof originalArgs == "object") 
    for (let arg in originalArgs)
      defaultValues[arg] = originalArgs[arg] || defaultValues[arg];

  // output the new object without altering the original
  return defaultValues;
}

describeBook({name:'A', author: 'B', section:'C'});



PreviousNext

Related