cachaito
4/24/2019 - 10:15 PM

ES6 destructing with arguments

// instead:
function myFunction(config) {
  console.log(config.text, config.line, config.truncate);
}

// we can do:
function myFunction({ text, line, truncate, extra = 'super!', foo: superExtra = 'wow' } = {}) {
  console.log(text, line, truncate, extra, superExtra); // Some value 0 100 super! wow
}
// The `= {}` it's a fallback object in case you didn't pass any. Lets you call the function without any parameters.

//usage for both examples:
myFunction({
  text: "Some value",
  line: 0,
  truncate: 100
});


// most advanced case:
const student = {
  name: 'John Doe',
  age: 16,
  scores: {
    maths: 74,
    english: 63,
    science: 85
  }
};

function displaySummary({ name, scores: { maths = 0, english = 0, science = 0 } = {} } = {}) {
 // some code
}


// even more nested:

var obj = {
  data: {
    priceTag: {
      name: 'a',
      survey: 'b',
      project: 'c',
      updated: 'd',
    }
  }
};

function setData({ data: { priceTag : { name, survey, project, updated } = {} } = {} } = {}) {
  console.log(name, survey, project, updated);
}

setData(obj);