is the var keyword really necessary?

Discussion in 'Javascript' started by Jack, Oct 4, 2004.

  1. Jack

    Jack Guest

    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,
     
    Jack, Oct 4, 2004
    #1
    1. Advertising

  2. Jack

    Lee Guest

    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.
     
    Lee, Oct 4, 2004
    #2
    1. Advertising

  3. Jack

    ZER0 Guest

    On 4 Oct 2004 07:39:22 -0700, Jack wrote:

    > 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"
     
    ZER0, Oct 4, 2004
    #3
  4. Jack <> spoke thus:

    > 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.

    --
    Christopher Benson-Manica | I *should* know what I'm talking about - if I
    ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
     
    Christopher Benson-Manica, Oct 4, 2004
    #4
  5. On 4 Oct 2004 07:39:22 -0700, Jack <> wrote:

    > 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.

    --
    Michael Winter
    Replace ".invalid" with ".uk" to reply by e-mail.
     
    Michael Winter, Oct 4, 2004
    #5
  6. On Mon, 4 Oct 2004 14:54:18 +0000 (UTC), Christopher Benson-Manica
    <> wrote:

    > Jack <> 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

    --
    Michael Winter
    Replace ".invalid" with ".uk" to reply by e-mail.
     
    Michael Winter, Oct 4, 2004
    #6
  7. On Mon, 04 Oct 2004 14:58:51 GMT, Michael Winter
    <> wrote:

    > On 4 Oct 2004 07:39:22 -0700, Jack <> wrote:
    >
    >> Is it recommended to use the var keyword when declaring a variable?

    >
    > [...] no [...]


    Oops. I was still considering the subject line which asked, "is the var
    keyword really necessary?"

    [snip]

    Mike

    --
    Michael Winter
    Replace ".invalid" with ".uk" to reply by e-mail.
     
    Michael Winter, Oct 4, 2004
    #7
  8. Michael Winter <> spoke thus:

    > 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).

    --
    Christopher Benson-Manica | I *should* know what I'm talking about - if I
    ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
     
    Christopher Benson-Manica, Oct 4, 2004
    #8
  9. On Mon, 4 Oct 2004 15:17:59 +0000 (UTC), Christopher Benson-Manica
    <> wrote:

    [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

    --
    Michael Winter
    Replace ".invalid" with ".uk" to reply by e-mail.
     
    Michael Winter, Oct 4, 2004
    #9
  10. Michael Winter wrote:
    > Christopher Benson-Manica wrote:

    <snip>
    >> 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.


    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.
     
    Richard Cornford, Oct 4, 2004
    #10
  11. On Mon, 4 Oct 2004 17:39:28 +0100, Richard Cornford
    <> wrote:

    [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

    --
    Michael Winter
    Replace ".invalid" with ".uk" to reply by e-mail.
     
    Michael Winter, Oct 4, 2004
    #11
  12. Jack wrote:
    > 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.
     
    Richard Cornford, Oct 4, 2004
    #12
  13. Jack

    bruce Guest

    (Jack) wrote in message news:<>...
    > 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.
     
    bruce, Oct 4, 2004
    #13
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Harald Kirsch

    Is volatile keyword necessary?

    Harald Kirsch, Mar 4, 2004, in forum: Java
    Replies:
    2
    Views:
    353
    Chris Uppal
    Mar 4, 2004
  2. GianGuz
    Replies:
    13
    Views:
    24,057
    Paavo Helde
    Dec 21, 2004
  3. Jim Langston
    Replies:
    7
    Views:
    363
    James Kanze
    Jul 7, 2007
  4. Bill Cunningham

    testing fclose...really necessary

    Bill Cunningham, Aug 8, 2008, in forum: C Programming
    Replies:
    12
    Views:
    612
    Richard Bos
    Aug 12, 2008
  5. walterbyrd
    Replies:
    116
    Views:
    2,044
    Arlo Belshee
    Jan 14, 2009
Loading...

Share This Page