JavaScript is a language of the Web. This series of articles will talk about my observations learned during my decade of software development experience with
JavaScript. I hope this series on JavaScript is giving you a good understanding and you are enjoying most parts of it.
Before moving further let us look at the previous articles of the series:
We will begin this article by reading this phrase "The Software shall be used for Good, not Evil." - Wikipedia
We will discuss in this section about how to write good code. Our code shall be clean, beautified, and other programmers are able to read & understand it; rather debug it. In order to achieve that we will look into the process of linting and then apply in the context of JavaScript.
Lint
It is a tool, which is used to flag code quality. It takes source code and find issues in it. This tool is available for many programming languages like C, PHP, etc. Linting is a process of running a program that will analyze code for potential errors.
As JavaScript is so popular and widely used, a lint for JavaScript is needed. In JavaScript, I am a fan of JSLint. This tool was developed by Douglas Crockford http://www.crockford.com/. Let us, deep-dive, into this tool.
JSLint
JSLint is a code quality tool for JavaScript. There are various advantages of this tool:
You can use an online version of JSLint and paste your JavaScript code & test it.
Here is a simple f1() function and we will validate in JSLint
The above will validate perfectly fine and this code will sail perfectly. To see how JSLint helps let me modify code & generate warnings:
It is so fantastic to do statistical analysis of your code so quickly! If we review four warnings, three are related to ‘whitespace’. One grabs my attention is
Expected ‘” use strict”: ‘before ‘var’. line 2 column 5
What is ‘use strict’?
We have not talked about ‘use strict’ rule so far. Nevertheless, this is an instruction that JavaScript code should be executed in ‘strict mode’. This directive was introduced in ECMAScript 5. You can define scope of ‘use strict’ to the beginning of a script (global scope) or a function but you cannot keep it within block statements enclosed in {} braces. The below picture could explain it better.
Advantages of script mode are
In the above example ‘y’ was not declared but referred, hence it caused below error ‘y is not defined’. Switch gear back to JSLint now
Other examples where JSLint could help in finding issues in code:
Upon execution, JSLint will give below message:
Summary
There are various advantages of JSLint and it helps programmers a lot. In the next article, I will talk about various options associated with it & how useful these are. Much more is coming in the ‘Voice of developer’ series; please share your feedback/comment below.