DEV Community

Discussion on: How do you order your functions?

Collapse
 
bytebodger profile image
Adam Nathaniel Davis • Edited

I always order them like this:

function first(){
  second()
  third()
}

function fourth(){
  // Whatever
}

function second(){
  fourth()
}

function third(){
  // Whatever
}

In other words, I order them alphabetically. Granted, it looks a little strange in this example, because these function names seem to imply a specific order. But that's not the case in "real" code.

I hate having to scroll up-then-down-then-up again as I search for a given function. So I put everything in alphabetical order. I even wrote a whole article about this a little while back:

dev.to/bytebodger/sorting-code-alp...

Collapse
 
savagepixie profile image
SavagePixie

I do a mix of alphabetical and abstraction order.

At the top I put all the helper functions sorted alphabetically and at the bottom the functions that the module exports (also sorted alphabetically).

For the same reason, I hate having to hunt functions up and down. Alphabetical order makes it much easier.

Collapse
 
aralroca profile image
Aral Roca

Oh nice. I sort imports alphabetically, but not functions. But It looks another alternative.

As a curiosity, if you have a module with a main function (export default) and other functions that are used by the "main" function. Do you put the main function at the top and the others at the bottom in alphabetical order, or do you also order the "main" function?

Collapse
 
bytebodger profile image
Adam Nathaniel Davis

Well, I spend most of my time doing React, which leverages functional components (very similar to a class). So with components, the component itself is the default export. Components can contain any number of functions. Inside the component, I always arrange my functions alphabetically.

In those cases where I'm defining standalone functions to be used across the app, I only ever define one function per file.