jsh
jsh

Reputation: 11

Function that Return Function -?

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]

Upvotes: 1

Views: 86

Answers (2)

vaibhav Prakash
vaibhav Prakash

Reputation: 101

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

Upvotes: 1

Jordan
Jordan

Reputation: 175

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

Upvotes: 0

Related Questions