JavaScript

js/no-var

Declare variables with const, or let when they are reassigned; never with var.

drobnastatycznefe-javascript

Dlaczego

var is scoped to the whole function, is hoisted as undefined, can be declared twice without an error and, at the top level of a classic script, becomes a property of window. Loops that create callbacks with var share one variable, a classic source of "every button opens the last item".

Poprawka

Use const by default and let for a value you reassign. Both are block scoped, cannot be redeclared and throw when read before their declaration. Load the script as a module so top-level names stay out of the global object.

Przykłady

// bad
for (var i = 0; i < buttons.length; i++) buttons[i].onclick = () => open(i)
// good
for (const [i, button] of buttons.entries()) button.addEventListener('click', () => open(i))

Źródła

Fakty

Identyfikator
js/no-var
Waga
drobna
Sprawdzanie
statyczne sprawdzane w kodzie źródłowym przez audit
Dotyczy plików
jsx html vue svelte astro
Uczy jej skill
fe-javascript JavaScript in the browser
Od wersji
0.1.0

Plik reguły na GitHubie

Przeczytaj w terminalu

npx github:dawidolko/frontend-skills explain js/no-var