1

So I've been writing a lot of JavaScript lately. Despite what many people say I think JavaScript can be a simple and beautiful language.

What I've pondered of late is how to structure the code so it is best readable to the human eye.

Sometimes there are cases like this:

mainFunction = function(){
  var init = function(){
    // do some initialization
    doSomeThing();
    doAnotherThing();
    window.addEventListener("scroll", someCallback);
  }
  var someCallback = function() {}
  var doSomeThing = function() {
    // code
  }

  var doAnotherThing = function() {
    // code
  }

  init();
}

You first have to define all functions before you can initialize some thing and finally do the stuff you wanted to do.

Now when I'm reading code, I always try to read it in a chronological order first, that's just how my brain works. But with JavaScript, the longer the code gets, the more complex I find to see where the start point is.

So I guess my questions are:

  1. Are most people reading code chronologically? Is chronological the best way for readability?
  2. How to achieve this in JavaScript? (What are some languages that do it better)
  3. What are some common JavaScript code writing philosophies out there?

1 Answers1

3

If putting the functions chronologically improves the readability of the code, it means that you are using functions wrong. The primary purpose of dividing the code to function is to reduce the amount of context you need to hold in your mind at any given time.

(functions have other usages when you use recursion or higher-order functions, but that's clearly not the case in your example(maybe except someCallback))

"The competent programmer is fully aware of the strictly limited size of his own skull; therefore he approaches the programming task in full humility, and among other things he avoids clever tricks like the plague."
Dijkstra (1972) The Humble Programmer (EWD340).

You break the big code into smaller functions so you can look at each function on it's own, and only have to think of what one function does at any given moment. Even with functions that call other functions(like the mainFunction) you don't think about what each of these functions does, instead abstracting them to atomic commands. This means you don't have to look at the entire flow of the program as a whole - so it doesn't matter if the functions are ordered according to that flow.

Idan Arye
  • 12,145