R
R
Ruslan2021-06-10 00:18:23
JavaScript
Ruslan, 2021-06-10 00:18:23

How does this code work?

Please tell me in simple words how the recursive function that checks the keys works in this code

<!DOCTYPE html>
<html>
<body>

  <div id="container"></div>

  <script>
    let data = {
      "Рыбы": {
        "форель": {},
        "лосось": {}
      },

      "Деревья": {
        "Огромные": {
          "секвойя": {},
          "дуб": {}
        },
        "Цветковые": {
          "яблоня": {},
          "магнолия": {}
        }
      }
    };

    function createTree(container, obj) {
      container.innerHTML = createTreeText(obj);
    }

    function createTreeText(obj) { // отдельная рекурсивная функция
      let li = '';
      let ul;
      for (let key in obj) {
        li += '<li>' + key + createTreeText(obj[key]) + '</li>';
      }
      if (li) {
        ul = '<ul>' + li + '</ul>'
      }
      return ul || '';
    }

    createTree(container, data);
  </script>
</body>
</html>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
asaiyo, 2021-06-10
@Romario5891

Information about the execution process of a running function is stored in its execution context.
An execution context is a special internal data structure that contains information about a function call. It includes a specific place in the code where the interpreter is located, local variables of the function, and other service information.
One function call has exactly one execution context associated with it.
When a function makes a nested call, the following happens:

  • The execution of the current function is suspended.
  • The execution context associated with it is stored in a special data structure - the execution context stack.
  • Nested calls are executed, for each of which a separate execution context is created.
  • After they complete, the old context is popped off the stack, and execution of the outer function resumes from where it left off.

https://learn.javascript.ru/recursion#kontekst-vyp...
The function iterates over the keys of the object and at the moment createTreeText(obj[key]) the interpreter takes the value of the key, stops, creates a new execution context, goes there and goes again with the beginning of the function, processing the value of the key. Sooner or later, an empty object gets into the function as an argument. An empty object has no keys, nothing to iterate over, the loop does not start, there is no one to call recursion, so the interpreter can go further through the body of the function, process if, return, and at the end return to the previous execution context to the place where it left off, namely . There it goes to the next key, again goes into recursion, then again sooner or later returns. '<li>' + key + сюда + '</li>'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question