no-var fix isn't safe in the global scope
See original GitHub issueI’m not sure what the project’s policy is about safety of fixes, but the no-var
can produce unsafe transformations when the var is global which makes it unsuitable for fixing arbitrary files.
This is a minimal example that isn’t safe (and here’s a demo page link to it):
var x = 10;
When fixed by eslint
it produces:
let x = 10;
However this isn’t equivalent as in the global context let
/const
statements have different semantics than var
, take this code for instance:
<script>
var x = 10;
</script>
<script>
var x = 20;
</script>
<script>
console.log(x);
console.log(window.x);
</script>
Running that code will print 20 twice, but in contrast if we run the eslint
“fixed” version:
<script>
let x = 10;
</script>
<script>
let x = 20;
</script>
<script>
console.log(x);
console.log(window.x);
</script>
In this case it will print 10
followed by undefined
, in addition the second script will simply throw an error that x
is already defined.
Now I’m not planning on using globals in this way in new code, but a lot of files in the code base are many years old and I know I’ve seen var someGlobalName
being used to add things as window.someGlobalName
so running the no-var
on the code base is very likely to break things. It would be nice at least to have an option to no-var
like ignore-global
or something like that to prevent breaking of such code.
Issue Analytics
- State:
- Created 6 years ago
- Comments:6 (5 by maintainers)
I think the best thing to do here would be to continue to report top-level global variables, but not autofix them. The fact that autofixing can cause code to break here seems like a bug to me.
I’ll work on this.