Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is this structure in javascript return({object}={})=>{more code}?

I’m trying to understand what this code is doing, it’s from a nodejs.
I don’t understand what is this structure is doing

return({object}={})=>{more code}

you can find the repository here:
https://github.com/howardmann/clean-node/blob/master/models/teacher/teacher.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let buildMakeTeacher = function(teacherValidator) {
  return ({
    name,
    subject,
    tenure = false
  } = {}) => {
    let {error} = teacherValidator({name, subject, tenure})
    if (error) throw new Error(error)

    return {
      getName: () => name,
      getSubject: () => subject,
      isTenure: () => tenure
    }
  }
}

>Solution :

In addition to answer by @Sarkar, the amount of curly braces here may shock you. The point of others (that don’t declare a scope) is object destructuring. Breaking down:

let {error} = teacherValidator({name, subject, tenure})

This line takes object returned by teacherValidator and extracts a key named error from it. If it returned, say, {error: 'Fail', errorcode: 1}, then error is assigned to 'Fail'.

return ({
  name,
  subject,
  tenure = false
} = {}) => { doSomething(); }

This creates an anonymous function with complex argument handling. It is (by calling result, implementation should differ) equivalent to:

return function(params={}) {
  let {name, subject, tenure=false} = params;
  doSomething();
}

This function:

  • When called without args, has params set to empty object;
  • When called with argument, extracts name and subject keys from it (undefined if not present) and tenure key (false if missing).
  • Performs some action with these args (checks error and returns object with 3 anonymous functions like getters)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading