CSE 341: Web Services

W01 Learning Activity: Coding Standards and ESLint

Overview

In this activity, you will learn why coding standards matter and how to use ESLint to check key standards for this course.

By the end of this page, you should understand the coding standards used in CSE 341, be able to add ESLint to your project, and know how to run lint checks as part of your normal workflow.

Preparation Material

What are coding standards?

Coding standards are shared rules about how code should be written. They help a team produce code that is easier to read, review, test, and maintain.

Good standards reduce avoidable differences between files and between developers. Instead of each person inventing their own style, the team agrees on a common approach.

Coding Standards in Industry

Most software companies have coding standards that developers must follow. These standards help teams write code that is consistent across many projects, easier to review, and easier to maintain over time.

Many companies keep their internal standards private, but some publish examples that anyone can read. For example, Google publishes style guides for TypeScript and Python. Microsoft publishes coding guidelines for projects such as TypeScript and Visual Studio Code, both of which are part of the JavaScript and TypeScript ecosystem.

Why coding standards matter

When code follows consistent standards, it becomes easier to understand what it is doing. You spend less time decoding style differences and more time thinking about logic.

Standards also reduce bugs. Some patterns are not just style choices. They help avoid outdated syntax, inconsistent error handling, or code that behaves in surprising ways.

This is especially important when using AI. AI-generated code may be functional, but it may not match the standards of your course or team. You still need to review it and change it so it matches.

Think like a team

Even when you are working alone in Week 1, you will practice the same habits that make team projects successful later. Consistent code will make things much easier for teammates and your future self.

CSE 341 coding standards

Throughout this course, you should follow these standards:

Standard Explanation
Use ESM syntax: import and export. ESM is the modern JavaScript module system used by current Node.js projects.
Do not use CommonJS syntax: require or module.exports. Mixing module systems causes confusion and makes project structure less predictable.
Use arrow functions and explicit return where needed. Arrow functions provide a consistent modern syntax and avoid some of the confusion around this in JavaScript.
Use async/await with try/catch instead of .then() and .catch(). This usually makes asynchronous server code easier to read and debug than chained promise handlers.
Use const by default. Use let only when a variable must be reassigned. Do not use var. This makes it clear when values are not meant to be reassigned.
Return after sending an Express response, such as return res.status(404).json({ message: 'Book not found' });. Returning the response helps prevent later code in the same handler from accidentally continuing after a response has already been sent.
Keep route handlers focused on request and response work. Move database access or larger logic into helper, model, or service functions when the code starts to grow. Small handlers are easier to test, review, and reuse as applications grow.
Use consistent JSON error response shapes, such as { "message": "Book not found" }. Predictable response shapes make client code easier to write and debug.
Do not show full error details to API clients. Log useful details on the server, but return safe messages in the response. Clients need useful status codes and safe messages, not stack traces or internal database details.
Use clear names for HTTP and data concepts. Conventional Express handlers may use req and res, but other variables should use descriptive names such as requestedId, book, books, or database. Descriptive variable names make code easier to review and reduce confusion when several records, ids, or collections are involved.
Validate required environment variables when the app starts so missing configuration fails clearly. Failing clearly at startup is better than letting the app run with missing configuration.

How ESLint helps

ESLint is a tool that checks your code for rule violations. It can warn you about patterns that do not match your standards and can sometimes fix simpler issues automatically.

ESLint does not replace thinking. It is a guardrail. It catches many mistakes quickly, but you still need to review your code for correctness and clarity.

Activity Instructions

Complete the following steps in the repository you created for Week 01.

Install ESLint

First, add ESLint as a development dependency.

  1. Open your Week 01 project in VS Code.
  2. In the terminal, install ESLint:
    npm install --save-dev eslint
  3. Open package.json and add the following lint and lint:fix scripts directly after your start and dev scripts:
      "scripts": {
        "start": "node --env-file=.env server.js",
        "dev": "nodemon --env-file=.env server.js",
        "lint": "eslint .",
        "lint:fix": "eslint . --fix",
        "test": "echo \"Error: no test specified\" && exit 1"
      },
    
  4. The script names are lint and lint:fix. The command each script runs starts with eslint, which is the linting tool.

Create the ESLint configuration file

Next, create an ESLint configuration that enforces the key standards for this course.

  1. Create a file named eslint.config.js in the root of your project.
  2. Paste in the following configuration:
export default [
  {
    ignores: ['node_modules/**']
  },
  {
    files: ['**/*.js'],
    languageOptions: {
      ecmaVersion: 'latest',
      sourceType: 'module',
      globals: {
        console: 'readonly',
        process: 'readonly'
      }
    },
    rules: {
      'prefer-arrow-callback': 'error',
      'no-var': 'error',
      'prefer-const': 'error',
      'arrow-body-style': ['error', 'always'],
      'consistent-return': 'error',
      'no-restricted-syntax': [
        'error',
        {
          selector: "CallExpression[callee.name='require']",
          message: 'Use ESM import syntax instead of require().'
        },
        {
          selector: "AssignmentExpression[left.object.name='module'][left.property.name='exports']",
          message: 'Use ESM export syntax instead of module.exports.'
        },
        {
          selector: "CallExpression[callee.property.name='then']",
          message: 'Use async/await instead of .then().'
        },
        {
          selector: "CallExpression[callee.property.name='catch']",
          message: 'Use try/catch with async/await instead of .catch().'
        },
        {
          selector: "ExpressionStatement > CallExpression[callee.object.name='res'][callee.property.name=/^(json|send)$/]",
          message: 'Return Express responses, such as return res.status(200).json(data).'
        },
        {
          selector: "ExpressionStatement > CallExpression[callee.property.name=/^(json|send)$/][callee.object.callee.object.name='res']",
          message: 'Return Express responses, such as return res.status(200).json(data).'
        }
      ]
    }
  }
];

Important note

This ESLint file enforces several important course standards, but not every quality issue can be checked automatically. You still need to read your code and make sure it is clear and correct.

Integrate linting into your workflow

Do not wait until the end of the assignment to run linting. Make it part of your normal development process.

  1. Run npm run lint after you finish a small piece of work.
  2. Some lint problems are safe to fix automatically. If ESLint reports problems that can be fixed automatically, you can fix them by running:
    npm run lint:fix
  3. Run npm run lint again to confirm the remaining issues are resolved.
  4. Before every commit or pull request, make sure your lint check passes.

Test code that does not pass

Temporarily add two lint problems to the files you created in a previous learning activity. This will let you see which problems ESLint can fix automatically and which problems you need to fix by hand.

  1. Open server.js and temporarily change const PORT to var PORT:
    var PORT = process.env.PORT;
  2. Open app.js and temporarily remove the return before the root route response:
    app.get('/', (req, res) => {
        res.status(200).json({ message: 'Server is running' });
    });
  3. Run the following command to check for errors:
    npm run lint
  4. Review the reported errors and notice how they point to course-standard violations.
  5. Run the automatic fixer:
    npm run lint:fix
  6. Open server.js and notice that ESLint changed var PORT back to const PORT automatically.
  7. Run lint again:
    npm run lint
  8. Notice that the missing return in app.js still needs to be fixed by hand. Add the return back:
    app.get('/', (req, res) => {
        return res.status(200).json({ message: 'Server is running' });
    });
  9. Run lint one more time:
    npm run lint
  10. Verify that everything passes.

Use this in your Week 01 and future assignments

You will be expected to run your lint process for all assignments in this course.

Submission

After you have completed all the learning activities for this week, return to Canvas to take the W01 Learning Activities quiz.

Other Links: