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

Time:06-30

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

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
    }
  }
}

CodePudding user response:

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)

CodePudding user response:

It's a anonymous function

this

(object)=>{more code}

is equivalent to this

function functionName(object){
   moreCode
}

your code example is a function called buildMakeTeacher which is returning an anonymous function which returns an object

CodePudding user response:

Read about closure and curry a bit it will give you a better perspective.

But basically that means this function returns a new function which returns an object with callable actions.

So to call it you should do something like buildMakeTeacher(someValidstor)({name: “foo”, subject: “bar”}).getSubject()

  • Related