ariya.io About Talks Articles

Complexity Analysis of JavaScript Code

2 min read

Nobody likes to read complex code, especially if it’s someone’s else code. A preventive approach to block any complex code entering the application is by watching its complexity carefully.

There are many measures of code complexity, the popular ones are McCabes cyclomatic complexity and Halsteads complexity. For JavaScript applications, there is a new tool from Phil Booth called JSComplexity which can be used to analyze your code and find out the complexity measures. Besides the above two code metrics, JSComplexity also produces the logical line of code (LOC) and the overall maintainability index. There is a whole page dedicated to explain the definition of these metrics and how they are computed.

JSComplexity can be used online via its web interface. Just paste your code and it will show you the analysis result. Under the hood, JSComplexity uses Esprima to parse your code and get the abstract syntax tree (AST). The syntax tree is then traversed according to the complexity analysis algorithm. For command-line use, you can use complexity-report package for Node.js.

Cyclomatic complexity is particularly interesting because (in laymen’s terms) it maps to the craziness of your program flow. If the code has tons of branches and paths, your cyclomatic complexity is catapulted to the sky. For the fun of it, here is the chart showing the cyclomatic complexity of some popular JavaScript libraries.

Of course, just like any other code metrics, code complexity should not be treated religiously. We also don’t have to think about complexity only in a one-dimensional way. In fact, correlating complexity with other variables usually reveals a much more useful insight. For example, plotting cyclomatic complexity vs time will display the dynamics of the code as the engineers refactor some parts or rewrite other stuff. Mapping complexity with different modules may give some hints as to which modules still need more TLC.

Use complexity measures to your advantage and hopefully you are better prepared in the battle zone!

Related posts:

♡ this article? Explore more articles and follow me Twitter.

Share this on Twitter Facebook