Generally, is there any standard best practice about the use of var keyword?
Yes there is. And that is to use var
every time.
But does it make any difference in something like a for loop?
There is no block-scope in javascript yet. So it makes no difference whatsoever. It is same as
var i;
for(i = 0; i < 10; i++) {
// you can access i inside
} // as well as outside the loop
Declaring variables without var
keyword throws an error when used in 'use strict'
. So it's always better to use var
keyword and avoid the ambiguity by attaching a property to window
if you want it to be global.
Ah forgot about let
keyword, which will make its way in ES6, which allows for a block scope. So it can be written as
for(let i = 0; i < 10; i++){
// i can be accessed here but not outside this block
}
Also it's worth noting is that
MDN: First, strict mode makes it impossible to accidentally create global
variables. In normal JavaScript mistyping a variable in an assignment
creates a new property on the global object and continues to "work"
(although future failure is possible: likely, in modern JavaScript)
which means, that it is considered an accidental mistake if you omit var
keyword and omitting it might not work in the future iterations of ECMAScript aka Javascript.
Use var
and you'll not pollute global context, your variables will be context-aware and be fail-proof for future versions of javascript, or in MDN's words, modern JavaScript.