Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any linter to warn about side-effects in JavaScript?

With the flexibility of JavaScript, we can write code full of side-effects, or just purely functional.

I have been interested in functional JavaScript, and wanting to start a project in this paradigm. And a linter about that can surely help me gathering good practices. Is there any linter to enforce pure functional and side-effect free style?

like image 812
Rufus Avatar asked Feb 03 '17 12:02

Rufus


People also ask

How do side effects happen in JavaScript statements?

A side effect is the modification of state through the invocation of a function or expression. In order for a function or expression to have a side effect, the state it modifies should be out of its local scope. Such as passing an object by reference through functions to be mutated and performing I/O operations.

What are JavaScript side effects?

What is a side effect in JavaScript? When we modify something, in JavaScript, we cause side effects, this simply means modifying or changing our code, causing it to have unpredictable behavior and mutability.

What are side effects in code?

A side effect is when a function relies on, or modifies, something outside its parameters to do something. For example, a function which reads or writes from a variable outside its own arguments, a database, a file, or the console can be described as having side effects.


2 Answers

Purity Analysis is equivalent to Solving the Halting Problem, so any kind of static analysis that can determine whether code is pure or impure is impossible in the general case. There will always be infinitely many programs for which it is undecidable whether or not they are pure; some of those programs will be pure, some impure.

Now, you deliberately used the term "linter" instead of static analyzer (although of course a linter is just a static analyzer), which seems to imply that you are fine with an approximate heuristic result. You can have a linter that will sometimes tell you that your code is pure, sometimes tell you that your code is impure, and most times tell you that it cannot decide whether your code is pure or impure. And you can have a whitelist of operations that are known to be pure (e.g. adding two Numbers using the + operator), and a blacklist of operations that are known to be impure (e.g. anything that can throw an exception, any sort of loops, if statements, Array.prototype.forEach) and do a heuristic scan for those.

But in the end, the results will be too unreliable to do anything serious with them.

like image 187
Jörg W Mittag Avatar answered Nov 23 '22 21:11

Jörg W Mittag


I haven't used this myself but I found this plugin for ESLint: https://github.com/jfmengels/eslint-plugin-fp

like image 25
Kushagra Sharma Avatar answered Nov 23 '22 22:11

Kushagra Sharma