JavaScript
js/no-var
Declare variables with const, or let when they are reassigned; never with var.
minorstaticfe-javascript
Why
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".
Fix
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.
Examples
// 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))Sources
Facts
- Id
js/no-var- Severity
- minor
- Check
- static checked in the source by
audit - Applies to
jsxhtmlvuesvelteastro- Taught by the skill
fe-javascriptJavaScript in the browser- Since version
- 0.1.0
Read it in the terminal
npx github:dawidolko/frontend-skills explain js/no-var