S
S
Sergey750il2015-08-22 01:54:54
JavaScript
Sergey750il, 2015-08-22 01:54:54

In what order do you write JavaScript code?

As far as I know, in order to understand the code, it is not recommended to use anonymous functions. But in what sequence is it correct to write functions and include them in a loop? Is it more correct to first write all the functions at the beginning of the document, and then initialize them, or is it possible to create a function above each cycle and then include it in the cycle?
From personal experience, it is very inconvenient when a function is described at the beginning of a document, but is included in the middle or towards the end.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vladlen Grachev, 2015-08-22
@gwer

The code should read like a story - from top to bottom. Each function must be followed by functions of the next level of abstraction. This allows you to read the code by successively descending the levels of abstraction as you read the list of functions.

This is an excerpt from Martin's Clean Code.
First comes a function with a high level of abstraction. It calls functions with less abstractness. These callable functions are described after the caller.

P
Pretor DH, 2015-08-22
@PretorDH

You ask the right questions...
First: Sequence in Java Script is not important, but you need to understand the flow of execution. For example:

function Mun(a){ return a };
  ( function(a){ console.log(a+' пошел'); } )( Mun('Первый') )
  /* Результат сразу же - Первый пошел */
  /* Мы создали функцию и выполнили её */

  function MunGo(a){ console.log(a+' ушел'); };
  function Mun(a){ return 'Не '+a };
  MunGo(Mun('Первый'));
  /* Выдаст - Не Первый ушел. */

Second: Understand the context of the described function, and don't call it from a different context.
... /* продолжая верхний пример*/ 
    (  function(a) {
          var Mun = function(a){ return a+' и третий'};
          MunGo ( Mun(a) );      /* Выдаст - Второй и третий ушел */
     }
   ) ( 'Второй');
  MunGo( Mun ('Второй') );    /* Выдаст - Не Второй ушел */

Third: The cycle should be as simple as possible. Take everything possible and impossible out of it. This will greatly speed it up. Try to do not only declarations, but even function calls, creating nodes, even accessing object fields outside the loop. Within the loop, operate only with local context variables.
Fourth: Use an anonymous context for all your code, and make interaction between different anonymous contexts through events.

V
Vladimir Martyanov, 2015-08-22
@vilgeforce

I'm writing any code from the beginning to the end of this very code.
"write all the functions at the beginning of the document, and then initialize them" - how is that? Does JS have function initialization?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question