Linters for beginners

Rob McBryde
6 min readDec 14, 2023

--

A quick-start introduction to what a code linter is. With an example of setting up a popular JavaScript example ESLint.

A linter is a static code analysis tool to help you improve your code. They exist for almost all programming languages but are particularly helpful for non-compiled languages such as JavaScript which don’t have a compiler to detect errors during runtime.

Benefits of a linter

Let’s look at the actual benefits that a linter tool can bring to your code:

  • Readable and consistent code. A linter allows us to define the style our code should adhere to and help us enforce that easily. For example, should our code statements end with a semi-colon, do we prefer single quotes over double quotes?
  • Reduced code smells. A linter can detect and fix technical issues such as code standards being broken. For example, particularly long functions or cyclomatic complexity within our code.
  • Simplifies code reviews. A linter can capture the teams agreed coding standards and apply them automatically saving wasted time debating minor syntax preferences or mistypes.
  • More secure and performant code. Some linters can even alert you to poor performing or insecure code.

Show me it in action

For a quick demo, we’re going to use ESLint, for a JavaScript project. Firstly, create yourself a brand new project (I’m going to use npm for this, but yarn will also work perfectly).

mkdir linting && cd linting
npm init
npm install eslint --save-dev

This will create your new project and install ESLint as a development dependency. Now let’s open up our project with your editor of choice, I’ll be using VSCode. Run the following command to initialise a new ESLint config file,

npm init @eslint/config

You will now be guided through a setup wizard via the command line to set up your linter. For this demo, I’m going to be opinionated for the sake of brevity, but feel free to explore these other options if they are more relevant to your project.

  • How would you like to use ESLint? — To check syntax, find, problems, and enforce code style
  • What type of modules does your project use? — JavaScript modules (import/export)
  • Which framework does your project use? — None of these
  • Does your project use TypeScript? — No
  • Where does your code run? — Node
  • How would you like to define a style for your project? — Use a popular style guide
  • Which style guide do you want to follow? — Google
  • What format do you want your config file to be in? — JSON

The wizard will be used to create a ‘.eslintrc.json’ file in the root of our project. We have opted to use the pre-configured set of linting rules that Google themselves use. We can modify these if we like to tailor them to our personal needs, but it’s a great starting point.

Now let’s create an example JavaScript file that we can practice with our new linter. Create a new folder called ‘src’ and inside it create a file named ‘greeter.js’ and enter the following code into it:

function greet(name) {
const options = {weekday: 'long', year: 'numeric', month: 'long', day: 'numeric'};
const now = new Date();
const formattedDate = now.toLocaleDateString('en-US', options);
return `Hello, ${name}! Today is ${formattedDate}.`;
}
 console.log(greet('Susan'))

Save the file and check you can run it via the command line:

node src/greeter.js
 Hello, Susan! Today is Tuesday, March 15, 2022.

Running our Linter

Now we have some working JavaScript code we can run our linter. First let’s add a command to so via our ‘package.json’ scripts section:

{
"name": "linting",
"version": "1.0.0",
"description": "",
"main": "greeter.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"lint": "eslint src/"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"eslint": "^8.11.0",
"eslint-config-google": "^0.14.0"
}
}

I have added the command ‘lint’ to run ESLint for all files within our ‘src’ directory. Lets try it on our command line by running:

npm run lint

Here we can see a number of errors being reported by our linter as violating the Google-defined code structure rules. There are a huge number of rules you can configure within your ‘.eslintrc.json’ file, let’s customise some of ours now.

Open your ‘.eslintrc.json’ file and add the following to your empty rules object.

"rules": {
"quotes": ["error", "double"],
"semi": ["warn", "never"]
}

We have informed our ESLint that an error should be reported if double quotation marks aren’t used. We have also added a rule allowing us to not require semi colons at the end of each statement. If a semi-colon is present then ESLint will raise a warning.

Re-run your linter once more and lets look at the output following our changes.

Fixing Lint violations

In order to fix our code, we simply make the changes our linter suggests. Firstly, we will add a JSDoc to our function to resolve this error in addition to removing the 2 spaces of indentation currently preceding all the lines of our function.

/**
* display a custom greeting with the current date
* @param {string} name to be displayed in custom greeting
* @return {string} the custom greeting
*/
function greet(name) {
const options = {weekday: 'long', year: 'numeric', month: 'long', day: 'numeric'};
const now = new Date();
const formattedDate = now.toLocaleDateString('en-US', options);
return `Hello, ${name}! Today is ${formattedDate}.`;
}
console.log(greet('Susan'))

Re-running our linter command shows this has fixed some of our errors:

Already we can see that updating all these meticulous formatting issues in our code can quickly become very tedious and time-consuming. Fear not there are editor extensions to the rescue!

ESLint VSCode Extension

To assist in identifying these issues without having to run our ESLint command, we can install the popular Microsoft ESLint extension in VSCode.

Once enabled, there is no configuration to be done (although you may need to restart your VSCode for it to take effect). The ESLint extension automatically detects our ‘.eslintrc.json’ configuration and gets to work in highlighting the issues in our code using the ESLint configuration rules we setup.

The extension highlights the warnings in yellow and errors in red squigglies (that’s a technical term).

We can now hover over each issue and es-lint will highlight the problem and offer us ‘Quick fix’ options to save typing ourselves, very handy. Of particular use is the ‘Fix all auto-fixable problems’ option.

This itself is helpful but it is still boring fixing these ourselves right? Don’t panic, there is some additional magic available. Within VSCode open Preference -> Settings and opt to open the settings in JSON. (Top right in VSCode settings). Paste the following extract into your settings.json file:

"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}

This setting will allow ESLint to auto-correct any fixable problems for you whenever you save a change to your file. To see it in action, make any change to our greeter.js file such as removing a semi-colon and then save the file and watch the magic happen.

Based on our lint settings, ESlint will automatically remove any semi-colons from the end of statements, replace any single quotes with double-quotes. Notice that it doesn’t auto-correct our max line length. violation when we initialise our ‘options’ variable. This is an example of something ESLint is not able to make an educated decision on how you would like to break this line up with carriage returns. But what it can do is still a big time saver.

To finish, I manually fix the line length on line 7 and run my manual my lint command once more to verify that it doesn’t report any violations: npm run lint

Conclusion

A linter helps us ensure quality code in our projects and often help teams work faster by cutting out necessary conversations over minor syntax issues during reviews. Every modern programming language has multiple linters you can try. Do a Google search and get your linter setup, it will improve your code and it’s the professional thing to do.

--

--

Rob McBryde

Test Engineer who empowers testers through coaching to enable their growth and knowledge of technology and automation.