javascript – How to find errors in code?

Question:

How to find errors in JavaScript code?
For example, I wrote a script, but it does not work. If we take, for example, Pascal, then there is a trace there: you press the space bar, and the code is executed line by line. You can see when it enters the cycle, how many times it runs there, when other things come out of it.

Answer:

Linters

At an early stage, even before the launch of the application, static code analyzers are very helpful, here are a few of the most popular:

  • JSLint from Grandpa Crockford, creator of JSON. It smells of valerian, but it works quite well, except for the fact that the settings are with a gulkin's nose.
  • JSHint is an excellent linter with flexible settings, 6k stars on github.
  • ESLint , and JSCS merged with it, is probably the coolest thing if you need to write your own plugins for some specific checks.

Surely you can integrate them into your development environment so that they work in the background and mark the errors found right in the code. For example, for WebStorm, it's enough just to check the box in the settings. By the way, WebStorm also has its own analyzer.

A little about typing

JavaScript does not (yet?) have the ability to specify types for function arguments, but you can use, for example, JSDoc . Write something like this (note the comment format):

/**
 * Creates a new Circle from a diameter.
 *
 * @param {number} d The desired diameter of the circle.
 * @return {Circle} The new Circle object.
 */
Circle.fromDiameter = function (d) {
    return new Circle(d / 2);
};

And now if somewhere fromDiameter is called, for example, with a string, then jsdoc in simple cases will be able to determine this before starting the program. In addition to this, jsdoc provides many other goodies, in addition to the main purpose – to generate documentation for your comments.

A more brutal option for real bearded gurus (for example, from the AngularJS team) is to take and rewrite everything in TypeScript, which is like JavaScript, but allows you to use (optionally!) Types for variables. And then, for example, you will immediately see (by compiler error) that you are calling a function that expects a string, passing it a number.

Debugging

Nobody canceled the good old Console.log('Ohh, shitt!') . But of course, you should not deny yourself the pleasure of using advanced debuggers. The same WebStorm has quite modern debugging capabilities, but all major browsers have one or another "development panel", with a debugger, profiler and other goodies. Set breakpoints (and not simple ones, but with a certain tricky condition, for example, to stop only for the second time, with a falling moon), look at the call stack, variable values ​​(change them on the fly at will), etc. For a quick start in chrome – press F12 , then you'll figure it out.

Scroll to Top