Blog>
Snippets

Fixing ESLint errors for a Node.js project

Display common ESLint errors in a Node.js context and how to resolve them according to best practices.
// Incorrect: missing semicolon and space before function parentheses
function helloWorld(){
  console.log('Hello, World')
}

// Corrected code:
function helloWorld() {
  console.log('Hello, World');
}
Fixes the missing semicolon at the end of the statement and adds a space before the function parentheses as required by ESLint rules.
// Incorrect: var is used instead of let or const
var name = 'Node.js';

// Corrected code:
const name = 'Node.js';
Replaces var with const for a variable that does not change to align with the best practices of using block-scoped variables.
// Incorrect: equality operator (==) instead of strict equality (===)
if (value == '123') {
  // do something
}

// Corrected code:
if (value === '123') {
  // do something
}
Replaces the == operator with === for a strict comparison, which is a common ESLint rule to avoid type coercion errors.
// Incorrect: unused variable
const unusedVariable = 'I will not be used';

// Corrected code:
// The unused variable is simply removed to satisfy ESLint no-unused-vars rule
Removes an unused variable as per the ESLint no-unused-vars rule which helps in keeping the code clean.
// Incorrect: callback without 'next' error handling
app.get('/', (req, res) => {
  throw new Error('Error!');
});

// Corrected code:
app.get('/', (req, res, next) => {
  try {
    throw new Error('Error!');
  } catch (error) {
    next(error);
  }
});
Adds error handling to an Express route by using the next function which is important for asynchronous error capturing in Express applications.