Search code examples
javascriptreactjsreact-hooksjavascript-objectsreadability

Understanding JavaScript object properties (functions) referencing other properties in same object


So I have stumbled upon a React Hooks based component that uses objects to categorize various functions for readability.

For eg.

const MyComponent = (props) => {
  const utilities = {
    utility1: () => {
      // ...some functionality
    },
    utility2: () => {
      // ...some functionality
    },
  };
  
  const renderers = {
    renderer1: () => {
      // ...some rendering logic
    },
    renderer2: () => {
      // ...some rendering logic
      return (
        <span>{renderers.renderer1()}</span>
      );
    },
  };

  return (
    // ...rendering logic
  );
};

What I want to understand is why is renderer2 working correctly even when it calls renderer1?

What I understand is that the object will be declared when the code is executed and the declaration is not complete till all properties are defined (this is just my noob understanding, I may be entirely wrong).

I would be really interested in knowing why this little bit of code works, especially why does it work correctly?

Also, on a side note, compared to Class-based components, I feel Hooks-based components are not very readable, and this approach tries to mitigate the problem. So I was wondering if this is the best way to make a Hooks-based component readable, or if there are other better approaches for the same?


Solution

  • What I understand is that the object will be declared when the code is executed and the declaration is not complete till all properties are defined

    This is not so. A variable declaration happens ahead of time - at compile time, before any code actually has had a chance to run. The assignement to a variable happens at runtime though. This includes evaluating the value being assigned.

    So in the case you're talking about, when the object being assigned to renderers is being evaluated, the renderers variable is actually already declared.

    Also, you have to consider the fact that renderers.renderer1() is not actually being called as part of the evaluation of this object - but only later on when renderers.renderer2() is actually be called, at which point both the object evaluation and the assignment will have completed, and thus renderers.renderer1() will be what you expect it to be.