ariya.io About Talks Articles

JavaScript Variable Scope and Highlight

2 min read

An interesting feature of many programmer’s editors is identifier highlighting. It makes easy to spot where a particular variable or function is used. With JavaScript as the language, highlighting is also useful since some JavaScript beginners are often confused by JavaScript function-level scope and its related effect of variable hoisting.

Implementing such a highlighting feature is usually far from trivial. Fortunately, we have many libraries which can resolve identifier scoping according to the language specification. One of them is escope (GitHub: github.com/Constellation/escope) from Yusuke Suzuki. While escope already implements a faithful scope analysis, it is often not very easy to use, hence I create a special microlibrary esrefactor (GitHub: github.com/ariya/esrefactor) which uses escope (after getting the syntax tree from Esprima) to locate occurrences of a given identifier.

Combining some language-related libraries like this (another demonstration of tools composition) gives a simple demo which can be tried live at esprima.org/demo/highlight.html. In the following screenshot, the cursor was placed in the last occurence of shuffled, where the word is enclosed with a subtle red border. All other references are highlighted as well. A special reference, marked with the ! symbol on the left gutter, denotes the location where the variable is declared. This also works well for function parameters.

shuffle2

Thanks to Orion editor, there is also a small indicator (it is even clickable) on the right scroll bar which gives the approximate location of the references relative to entire code. This is handy if the code is very large so you don’t need to scroll endlessly to go to a particular reference.

Since the demo uses escope, the scope analysis follows the ECMAScript 5.1 specification faithfully. For example, look at this rather convoluted code fragment and see how the highlight skips some variables even though they share the same name with the one under the cursor.

nested

Next week, we will see the logical next step of this feature: rename refactoring. Stay tuned!

Related posts:

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

Share this on Twitter Facebook