Day 67.

Questions on Factory Functions

·

2 min read

//string as param
const FactoryFunction = string => {
  //arrow function named capitalizeString 
  const capitalizeString = () => string.toUpperCase();
  //arrow function named printString
  const printString = () => console.log(`--
  -${capitalizeString()}---`);
  //can access capitalizeString bc it's within the function
  return {printString };
  }
//create object 'taco' using factory function
//which is essentially calling the function with param
const taco = FactoryFunction('taco');

printString(); //ERROR not defined
capitalizeString();//ERROR not defined
taco.capitalizeString();// ERROR not defined
taco.capitalizeString(); //ERROR

taco.printString(); //CLOSURE

1. In this example, why doesn't taco.capitalizeString() work ? taco is an instance of FactoryFunction, and it would have capitalizeString() function defined as well, so I'd assume I can access it through the dot notation.

\=> Factory functions return objects. Here, it returns {printString}. It's a shorthand for {printString : printString}. We have an object with a method prinstString. You can access it with taco.printString(). Factory functions contain local variables/functions that you don't want to export outside. taco.capitalizeString() doesn't work because capitalizeString() is a local function inside the factory function and it has not been exported.

Question 2.

const counterCreator = () => {
  let count = 0;
  return () => {
    console.log(count);
    count++;
    };
};
// why need parentheses when `counterCreator` is already a function?(returns an arrow function above)
//Can't you just assign that arrow function to `counter`? Why execute it with parentheses?
const counter = counterCreator();

//why would variable `counter` have parentheses?
//to execute it? 
counter();//0
counter();//1
counter();//2
counter();//3

Why do you need parentheses when counterCreator is already a function?(returns an arrow function above) Can't you just assign that arrow function to counter? Why execute it with parentheses?

\=> You need to execute counterCreator function for it to return the object. Remember, a function is just a formula written out, if you want to run it, you need parentheses.