About Collections Archives

Most popular JavaScript keywords

2 min read

Most popular keywords? The quick short answer is: it depends.

While investigating the proposal for a faster isKeyword() function in Esprima, I decided to see the frequency of JavaScript keywords appearing in most common libraries. Esprima already has a selection of popular libraries as part of its comprehensive benchmark suite. When I eliminated the duplicated versions (so that each library is represented only once), the distribution of the keywords is depicted in the following chart. The dominant ones are this, function, if, return, and var, followed by a long tail of other keywords.

There are several things which are validated by the above data. For example, it is expected that finally should occur less, or at least the same, as try. Due to then nature of the construct, case typically shows up more often than its parent switch. Also it will be weird if else is found more than if, same case with do and while pair.

Obviously the above beautiful color chart is only for keywords in libraries and frameworks. For real-world user applications, the situation could be different. If you are interested in running the analysis on your own code, use the following quick tool keyword.js:

var fs = require('fs'),
    esprima = require('esprima'),
    files = process.argv.splice(2);
files.forEach(function (filename) {
    var content = fs.readFileSync(filename, 'utf-8'),
        tokens = esprima.parse(content, { tokens: true }).tokens;
    tokens.forEach(function (token) {
        if (token.type === 'Keyword') {

and run it with Node.js:

node keyword.js myapp.js mylib.js others/*.js | sort | uniq -c | sort -nr

or alternatively, to go recursive in a certain directory:

find /path/to/dir -type f -name '*.js' -exec node keyword.js '{}' + |
  sort | uniq -c |  sort -nr

What do you get for your project?

Related posts:

♡ this article? Explore more, check the archives, or follow me Twitter.

Share this on Twitter Facebook Google+

comments powered by Disqus