1

I'm just starting to learn JavaScript and doing some coding practice. Sorry, this may be a silly question. I'm having hard time understanding the answer of below function that returns function.

accessor function takes an object and returns a function.
The returned function can access properties and values of the given object.

The part that I don't understand is how the returned function is accessing the property and value of the object without defining in global scope?

Sorry, if the question is unclear. I want to know why the returned function is able to access property and value without using for in.. loop.

I have been trying to find article/ blog post about this but haven't been able to find anything. If you can clarify, I appreciate it!!

const accessor = obj => {
  return (prop, value) => {
    if (value === undefined) {
      return obj[prop];
    } else {
      obj[prop] = value;
    }
  };
};

accessExample = accessor({ foobar: [7, 8, 9] });
accessExample('foobar');

//returns [7, 8, 9]
jsh
  • 11
  • 1
  • It’s able to access the `obj` through a [closure](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) – Mark Oct 17 '18 at 06:53
  • 1
    https://stackoverflow.com/questions/7629891/functions-that-return-a-function – Tomasz Waszczyk Oct 17 '18 at 06:57
  • Possible duplicate of [Functions that return a function](https://stackoverflow.com/questions/7629891/functions-that-return-a-function) – MrMaavin Oct 17 '18 at 07:04

2 Answers2

1

This happens because of closures. All functions in javascript form closures. You can read more about it from here Closures

0

Functions literally create scope in JS. Any variable can be accessed within nested functions. Here is a good link to explain

Jordan
  • 176
  • 10