Skip to main content

Command Palette

Search for a command to run...

JavaScript partial functions

Updated
1 min read

Consider (https://jsfiddle.net/h9jz2yfs/)

// currying
function who(func) {
    let profile='';

     return function(name) {
      profile+=`my name is ${name} `;
    return function(age) {
        profile+=`and i'm ${age} years old `;
      return function(hobby) {
          profile+=`and my hobby is ${hobby}.`;
        func.call({}, profile);
      }
    }
  }
}

//who(p => console.log(p))('bob')(41)('programming');
const bob=who(p => console.log(p))('bob')(41);
bob('programming');            // what is bob's hobbey?

Output

"my name is bob and i'm 41 years old and my hobby is programming."

This is an example of partial function. This is constructed by returning function inside function inside function... Also notice that variable profile is persistent (it saves its state) over subsequent function calls.