Day 61.

Scope in Factory Functions

·

2 min read

const FactoryFunction = string => { 
    const capitalizeString = () => string.toUpperCase(); 
    const printString = () => console.log(----${capitalizeString()}----); //"printString has access to everything inside the FactoryFunction" 
return { printString }; 
};

const taco = FactoryFunction('taco');
  1. The video in the lesson says "printString has access to all functions inside FactoryFunction ". Is it only saying that because there's only one other function (capitalizeString) defined in FactoryFunction and capitalizeString is used in the function body of printString?

  2. But if FactoryFunction had more functions defined inside it, such as function repeatString and function lowercaseString, would printString, which is the object that's returned from the FactoryFunction , also has access to all three other functions?

\=> 1. Function printString has access to all functions inside FactoryFunction because they're all within the same function block. Try thinking them defined in a global scope. If you define functions in a global scope they would all have access to each other.

\=> 2. if I wanted to use repeatString, given that printString is the only one that's being returned, I'd have to include it in the function body of printString. The only way I can use the above function is through the object that's being returned from the factory function. I have to use those functions in printString. If I don't, I wouldn't have access to those.
Unless I return those other functions in the object as well.