is the var keyword really necessary?

J

Jack

Hi,

Is it recommended to use the var keyword when declaring a variable?

IE lets me create a variable with var, then create the same one again
with no problem.
Also it lets me create a variable without the var keyword. As such the
code below works fine:

<html>
<script>
test = 1;
var test2 = 2;
var test = 3;
var test2 = 4;
alert(test);
alert(test2);
</script>
</html>

Also, is there a good reason not to do for statements like:

for (li=0;li<10;li++){;}

instead of:

for (var li=0;li<10;li++){;}


Cheers,
 
L

Lee

Jack said:
Hi,

Is it recommended to use the var keyword when declaring a variable?

IE lets me create a variable with var, then create the same one again
with no problem.
Also it lets me create a variable without the var keyword. As such the
code below works fine:

The var keyword doesn't do anything unless you are defining
functions in your code, because without functions, all variables
are global.

When you start defining functions, you need to learn about scope
rules and how the "var" keyword changes the scope of variables.
 
Z

ZER0

Is it recommended to use the var keyword when declaring a variable?

yes, 'cause you define the scope of your variables with var keyword.

for example:

var i=12; /* i is global */

function foo(){
var j=2; /* j is local */
alert(i+j);
}

alert(i);
foo();
alert(j); /* error! j is local */

try the same code without var keyword:

i=12; /* i is global */

function foo(){
j=2; /* j is global as well */
alert(i+j);
}

alert(i);
foo();
alert(j);

As you see, without the var keyword all variables are global, and you could
do overwrite some variable from function to another function.

In addition, with "var" keyword you declare the variable, even if you don't
assign it some value:

var x;

alert("x" in window); //true
alert("y" in window); //false

Hope it helps.

P.S.
Sorry for my english.

--
ZER0://coder.gfxer.web-designer/

~ "Massi' che e' uno standard, e' uno standard proprietario."
(Gio')

on air ~ "Motion City Soundtrack - My Favorite Accident"
 
C

Christopher Benson-Manica

Jack said:
Also, is there a good reason not to do for statements like:
for (li=0;li<10;li++){;}
instead of:
for (var li=0;li<10;li++){;}

This second one is misleading, because li has function scope, not
block scope (as the code seems to suggest). I personally choose
neither, because as written they're hard to read.

for( li=0; li < 10; li++ ) {;}

Much easier IMHO.
 
M

Michael Winter

Is it recommended to use the var keyword when declaring a variable?

For global variables, no, but it is considered good form. Starting with
the var keyword makes it clear that the statement is a variable
declaration (and possibly initialisation).
IE lets me create a variable with var, then create the same one again
with no problem.

I don't think it's a syntax error, but there isn't much point.
Also it lets me create a variable without the var keyword. As such the
code below works fine:

<html>
<script>
test = 1;
var test2 = 2;
var test = 3;
var test2 = 4;
alert(test);
alert(test2);
</script>
</html>

It is fine, because all of the variables are global.

myVar = 1;

and

var myVar = 1;

are identical at that scope level. The var keyword becomes very different
within functions.
Also, is there a good reason not to do for statements like:

for (li=0;li<10;li++){;}

instead of:

for (var li=0;li<10;li++){;}

Again, in global scope, there isn't any problem. However, consider this[1]:

function myFunction() {
for(i = 0; i < 5; ++i) {
// do something
myFunction();
}
}

When the function is called recursively, the variable, i, is reset to zero
every time. When earlier invocations eventually regain control, i will
always be five. That isn't likely to be the intended action.

Getting into the habit of always using the var keyword is a good thing to
do, in my opinion. It avoids problems that could arise if you forget to
add it one time. Similarly, variables should *always* be limited in scope
as much as possible. There are many ways to avoid placing globals
everywhere, not limited to using objects and closures. Not only does it
reduce the chances of errors, it also makes code more reusable by not
polluting the global namespace.

Mike


[1] Ignore the infinite recursion for the moment. That isn't important for
this example.
 
M

Michael Winter

Jack <[email protected]> spoke thus:
[snip]
for (var li=0;li<10;li++){;}

This second one is misleading, because li has function scope, not block
scope (as the code seems to suggest).

That is true, if you're coming from a block scope background (I'm very
much used to both), but most familiar with Javascript won't be confused by
it. Moreover, if li is only used within the loop, there isn't much harm
and I personally prefer it (though I'm used to function scope, I do prefer
block scope).
I personally choose neither, because as written they're hard to read.

for( li=0; li < 10; li++ ) {;}

As in

var li;

for( li=0; li < 10; li++ ) {;}

or do you use globals unless a situation demands otherwise?

Mike
 
C

Christopher Benson-Manica

Michael Winter said:
That is true, if you're coming from a block scope background (I'm very
much used to both), but most familiar with Javascript won't be confused by
it. Moreover, if li is only used within the loop, there isn't much harm
and I personally prefer it (though I'm used to function scope, I do prefer
block scope).

Well, if it's only used for the one loop, then it's fine. But in a
complex script function with multiple loops, the C++ method would be

for( int i=0; i < 10; i++ ) //
....
for( int i=0; i < 10; i++ ) //

Is redeclaring variables legal in JavaScript? jslint, in any case,
does not allow it.
var li;
for( li=0; li < 10; li++ ) {;}

I do that, on the assumption that redeclaration of variables is not
technically legal; I may, of course, be mistaken (or misled by jslint,
as the case may be).
 
M

Michael Winter

On Mon, 4 Oct 2004 15:17:59 +0000 (UTC), Christopher Benson-Manica

[snip]
Well, if it's only used for the one loop, then it's fine. But in a
complex script function with multiple loops, the C++ method would be

for( int i=0; i < 10; i++ ) //
...
for( int i=0; i < 10; i++ ) //

In something like that, I'd probably move the declaration to the start of
the function. I'm used to doing that with MSVC++ which doesn't count the
variable declaration list of a for loop as a block (unless I'm getting
confused with another compiler...).
Is redeclaring variables legal in JavaScript? jslint, in any case,
does not allow it.

I don't read anything in ECMA-262, and Mozilla (the most pedantic browser
I have) doesn't complain, so I'd say it's fine. Don't forget: JSLint
comments on style, as much as syntax, in order to prevent accidental
errors.

[snip]

Mike
 
R

Richard Cornford

Michael said:
Christopher Benson-Manica wrote:

I don't read anything in ECMA-262, and Mozilla (the most
pedantic browser I have) doesn't complain, so I'd say it's
fine. Don't forget: JSLint comments on style, as much as
syntax, in order to prevent accidental errors.

ECMA 262 does explicitly cover this in section 10.1.3 Variable
Instantiation:-

| Fore each VariableDeclaration or VariableDeclarationNoIn in
| the code, create a property of the variable object ...
| ... If there is already a property of the variable object
| with the name of a declared variable, the value of the
| property and its attributes are not changed. ...

And variable instantiation only happens once upon entering an execution
context. So you can declare the same variable as often as you like, only
one will ever exist as a result. Though it would be wasteful in time
take for variable instantiation and needlessly downloaded bytes to
re-declare variables (but not really the end of the world if it was only
re-declaring the same counter in two consecutive - for - loops).

Richard.
 
M

Michael Winter

On Mon, 4 Oct 2004 17:39:28 +0100, Richard Cornford

[snip]
ECMA 262 does explicitly cover this [redeclaring variables] in section
10.1.3 Variable Instantiation:-

Ah. I didn't look in that section. I only checked 12.2 - Variable
statement, despite 10.1.3 being referenced twice.

[snip]

Thanks.

Mike
 
R

Richard Cornford

Jack said:
Is it recommended to use the var keyword when declaring
a variable?

Yes.

Even when a global variable can be created (in effect) by nothing more
than assigning a value to an otherwise undeclared identifier, explicitly
declaring that identifier as a global variable in the global scope makes
it clear that the identifier is intended to be a global variable. That
clarity if for the benefit of humans reading the code; it prevents them
form wasting time trying to work out if the variable in question was
intended to be a global variable or whether they are looking at an
authoring mistake.

It is also the case that explicitly declared global variables are safer
to use because a read operation on an undeclared global variable that
takes the form of its (unqualified) identifier will throw a TypeError.
So code where one function attempts to create a global variable by
assigning to it, while another function reads from it, will error in the
second function if the first has not already been successfully executed.
If the same variable was explicitly declare the attempt to read its
value might return undefined but it would not error (the latter being
much easier to cope with).

Once you are writing functions - var - becomes essential because code
that attempts to use exclusively global variables soon ends up an
unmanageable spaghetti, where unplanned interactions in the global scope
produce intermittent errors that are difficult to identify and correct
(such code quickly exceeds the limited human ability to comprehend its
complexity). One programming principle, that certainly is applicable to
javascript, is: never give a variable more scope than it absolutely
needs. And using - var - to declare local variables in functions is the
mechanism for doing that.

Richard.
 
B

bruce

Hi,

Is it recommended to use the var keyword when declaring a variable?

IE lets me create a variable with var, then create the same one again
with no problem.
Also it lets me create a variable without the var keyword. As such the
code below works fine:

<html>
<script>
test = 1;
var test2 = 2;
var test = 3;
var test2 = 4;
alert(test);
alert(test2);
</script>
</html>

Also, is there a good reason not to do for statements like:

for (li=0;li<10;li++){;}

instead of:

for (var li=0;li<10;li++){;}


Cheers,


If a system gets large enough, eventually you will use a field as
a local variable (without var), without realizing that it is a global
variable already. And finding the error isn't very easy.
For readability alone, it's advised to use var. It's also an act
of consideration for the next guy who comes along and has to read the
code.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top